Save DataTable Into ViewState and Bind Gridview Without DataBase Using ASP.Net

Background

I have read many forum posts regarding how to save a DataTable in Viewstate and display those records in a GridView without saving in the database. In consideration of those requirements I decided to write an article on it. So let us start creating a web application as:

  1. "Start" - "All Programs" - "Microsoft Visual Studio 2010".
  2. "File" - "New WebSite" - "C#" - "Empty WebSite" (to avoid adding a master page).
  3. Provide the web site a name such as "SaveDataTableInViewsate" or another as you wish and specify the location.
  4. Then right-click on Solution Explorer - "Add New Item" - Add Web Form.
  5. Drag and drop one button and three textBoxes onto the <form> section of the Default.aspx page.
  6. Now the default.aspx page source code will look such as follows.

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>  
  2.   
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  4. <html xmlns="http://www.w3.org/1999/xhtml">  
  5. <head runat="server">  
  6.     <title></title>  
  7. </head>  
  8. <body style="background-color: #0000FF">  
  9.     <form id="form1" runat="server">  
  10.     <table style="color: White;margin-top:30px;margin-left:10px">  
  11.         <tr>  
  12.             <td>  
  13.                 Author Name  
  14.             </td>  
  15.             <td>  
  16.                 Book Name  
  17.             </td>  
  18.             <td>  
  19.                 Book Type  
  20.             </td>  
  21.             <td>  
  22.                 Publisher  
  23.             </td>  
  24.         </tr>  
  25.         <tr>  
  26.             <td>  
  27.                 <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>  
  28.             </td>  
  29.             <td>  
  30.                 <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>  
  31.             </td>  
  32.             <td>  
  33.                 <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>  
  34.             </td>  
  35.             <td>  
  36.                 <asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>  
  37.             </td>  
  38.         </tr>  
  39.         <tr>  
  40.             <td>  
  41.             </td>  
  42.             <td>  
  43.             </td>  
  44.             <td>  
  45.             </td>  
  46.             <td>  
  47.                 <asp:Button ID="AddProduct" runat="server" Style="color: White" Text="Add Product"  
  48.                     OnClick="AddProduct_Click" BackColor="#999966" />  
  49.             </td>  
  50.         </tr>  
  51.     </table>  
  52.      
  53.     <div style="margin-left:10px;margin-top:10px">  
  54.      <asp:GridView ID="GridView1" AutoGenerateColumns="false" runat="server" CellPadding="4"  
  55.         ForeColor="#333333" GridLines="None">  
  56.         <AlternatingRowStyle BackColor="White" />  
  57.         <Columns>  
  58.             <asp:BoundField HeaderStyle-Width="120px" HeaderText="Author  Name" DataField="AuthorName" />  
  59.             <asp:BoundField HeaderStyle-Width="120px" HeaderText=" Book Name" DataField="BookName" />  
  60.             <asp:BoundField HeaderStyle-Width="120px" HeaderText=" Book Type" DataField="BookType" />  
  61.             <asp:BoundField HeaderStyle-Width="120px" HeaderText="Publisher" DataField="Publisher" />  
  62.         </Columns>  
  63.         <EditRowStyle BackColor="#2461BF" />  
  64.         <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />  
  65.         <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />  
  66.         <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />  
  67.         <RowStyle BackColor="#EFF3FB" />  
  68.         <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />  
  69.         <SortedAscendingCellStyle BackColor="#F5F7FB" />  
  70.         <SortedAscendingHeaderStyle BackColor="#6D95E1" />  
  71.         <SortedDescendingCellStyle BackColor="#E9EBEF" />  
  72.         <SortedDescendingHeaderStyle BackColor="#4870BE" />  
  73.     </asp:GridView>  
  74.     </div>  
  75.     </form>  
  76. </body>  
  77. </html> 

Now switch to design mode, it will be like this.

 
 
Now switch to the default.aspx.cs code behind file and write the following code to create and save the datatable into viewstate and bind the GridView as:
  1. private void AddDefaultFirstRecord()  
  2.  {  
  3.      //creating dataTable   
  4.      DataTable dt = new DataTable();  
  5.      DataRow dr;  
  6.      dt.TableName = "AuthorBooks";  
  7.      dt.Columns.Add(new DataColumn("AuthorName"typeof(string)));  
  8.      dt.Columns.Add(new DataColumn("BookName"typeof(string)));  
  9.      dt.Columns.Add(new DataColumn("BookType"typeof(string)));  
  10.      dt.Columns.Add(new DataColumn("Publisher"typeof(string)));  
  11.      dr = dt.NewRow();  
  12.      dt.Rows.Add(dr);  
  13.      //saving databale into viewstate   
  14.      ViewState["AuthorBooks"] = dt;  
  15.      //bind Gridview  
  16.      GridView1.DataSource = dt;  
  17.      GridView1.DataBind();  
  18.  } 
 Now call the above function at Page Load so that the initial records will be added into the view state and GridView as:
  1. protected void Page_Load(object sender, EventArgs e)  
  2.     {  
  3.         if (!IsPostBack)  
  4.         {  
  5.             AddDefaultFirstRecord();  
  6.         }  
  7.     } 
Now create a function with the following code that will save the records into a data table using view state and will be available to be bound to the GridView as:
  1. private void AddNewRecordRowToGrid()  
  2.    {  
  3.        // check view state is not null  
  4.        if (ViewState["AuthorBooks"] != null)  
  5.        {  
  6.            //get datatable from view state   
  7.            DataTable dtCurrentTable = (DataTable)ViewState["AuthorBooks"];  
  8.            DataRow drCurrentRow = null;  
  9.   
  10.            if (dtCurrentTable.Rows.Count > 0)  
  11.            {  
  12.   
  13.                for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)  
  14.                {  
  15.   
  16.                    //add each row into data table  
  17.                    drCurrentRow = dtCurrentTable.NewRow();  
  18.                    drCurrentRow["AuthorName"] = TextBox1.Text;  
  19.                    drCurrentRow["BrandName"] = TextBox2.Text;  
  20.                    drCurrentRow["Warrenty"] =TextBox3.Text;  
  21.                    drCurrentRow["Price"] =TextBox4.Text;  
  22.   
  23.   
  24.                }  
  25.                //Remove initial blank row  
  26.                if (dtCurrentTable.Rows[0][0].ToString() == "")  
  27.                {  
  28.                    dtCurrentTable.Rows[0].Delete();  
  29.                    dtCurrentTable.AcceptChanges();  
  30.   
  31.                }  
  32.   
  33.                //add created Rows into dataTable  
  34.                dtCurrentTable.Rows.Add(drCurrentRow);  
  35.                //Save Data table into view state after creating each row  
  36.                ViewState["AuthorBooks"] = dtCurrentTable;  
  37.                //Bind Gridview with latest Row  
  38.                GridView1.DataSource = dtCurrentTable;  
  39.                GridView1.DataBind();  
  40.            }  
  41.        }  
  42.    } 
Call the function above to add book details in the button click as:
  1. protected void AddProduct_Click(object sender, EventArgs e)  
  2.   {  
  3.       AddNewRecordRowToGrid();  
  4.   } 
 Now the entire code of the default.aspx.cs page will be such as follows:
  1. using System;  
  2. using System.Data;  
  3. public partial class _Default : System.Web.UI.Page  
  4. {  
  5.   
  6.     protected void Page_Load(object sender, EventArgs e)  
  7.     {  
  8.         if (!IsPostBack)  
  9.         {  
  10.             AddDefaultFirstRecord();  
  11.         }  
  12.     }  
  13.     protected void AddProduct_Click(object sender, EventArgs e)  
  14.     {  
  15.         AddNewRecordRowToGrid();  
  16.     }  
  17.   
  18.     private void AddDefaultFirstRecord()  
  19.     {  
  20.         //creating dataTable   
  21.         DataTable dt = new DataTable();  
  22.         DataRow dr;  
  23.         dt.TableName = "AuthorBooks";  
  24.         dt.Columns.Add(new DataColumn("AuthorName"typeof(string)));  
  25.         dt.Columns.Add(new DataColumn("BookName"typeof(string)));  
  26.         dt.Columns.Add(new DataColumn("BookType"typeof(string)));  
  27.         dt.Columns.Add(new DataColumn("Publisher"typeof(string)));  
  28.         dr = dt.NewRow();  
  29.         dt.Rows.Add(dr);  
  30.         //saving databale into viewstate   
  31.         ViewState["AuthorBooks"] = dt;  
  32.         //bind Gridview  
  33.         GridView1.DataSource = dt;  
  34.         GridView1.DataBind();  
  35.     }  
  36.     private void AddNewRecordRowToGrid()  
  37.     {  
  38.         // check view state is not null  
  39.         if (ViewState["AuthorBooks"] != null)  
  40.         {  
  41.             //get datatable from view state   
  42.             DataTable dtCurrentTable = (DataTable)ViewState["AuthorBooks"];  
  43.             DataRow drCurrentRow = null;  
  44.   
  45.             if (dtCurrentTable.Rows.Count > 0)  
  46.             {  
  47.   
  48.                 for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)  
  49.                 {  
  50.   
  51.                     //add each row into data table  
  52.                     drCurrentRow = dtCurrentTable.NewRow();  
  53.                     drCurrentRow["AuthorName"] = TextBox1.Text;  
  54.                     drCurrentRow["BookName"] = TextBox2.Text;  
  55.                     drCurrentRow["BookType"] =TextBox3.Text;  
  56.                     drCurrentRow["Publisher"] =TextBox4.Text;  
  57.   
  58.   
  59.                 }  
  60.                 //Remove initial blank row  
  61.                 if (dtCurrentTable.Rows[0][0].ToString() == "")  
  62.                 {  
  63.                     dtCurrentTable.Rows[0].Delete();  
  64.                     dtCurrentTable.AcceptChanges();  
  65.   
  66.                 }  
  67.   
  68.                 //add created Rows into dataTable  
  69.                 dtCurrentTable.Rows.Add(drCurrentRow);  
  70.                 //Save Data table into view state after creating each row  
  71.                 ViewState["AuthorBooks"] = dtCurrentTable;  
  72.                 //Bind Gridview with latest Row  
  73.                 GridView1.DataSource = dtCurrentTable;  
  74.                 GridView1.DataBind();  
  75.             }  
  76.         }  
  77.     }  
  78.   

Now run the application, the page will look as follows: 
 
 
 
Now add some details into the textboxes above and click on the Add Book Details button. Then the records that were saved in the DataTable will displayed in the GridView as:
 
 
Now add another book details. It will be added in the existing one as:
 
 
 
Similar to the above you can add n number of records up to the datatable capacity.
 
Note
  • For the detailed code please download the sample Zip file.
  • Do proper validation such as date input values when implementing.
Summary

From all the examples above we have learned how to save a DataTable into viewstate and display those records into GridView without saving records into the database. I hope this article is useful for all readers. If you have a suggestion then please contact me.

Up Next
    Ebook Download
    View all
    Learn
    View all