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. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  3. <html xmlns="http://www.w3.org/1999/xhtml">
  4. <head runat="server">
  5. <title></title>
  6. </head>
  7. <body style="background-color: #0000FF">
  8. <form id="form1" runat="server">
  9. <table style="color: White;margin-top:30px;margin-left:10px">
  10. <tr>
  11. <td>
  12. Author Name
  13. </td>
  14. <td>
  15. Book Name
  16. </td>
  17. <td>
  18. Book Type
  19. </td>
  20. <td>
  21. Publisher
  22. </td>
  23. </tr>
  24. <tr>
  25. <td>
  26. <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
  27. </td>
  28. <td>
  29. <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
  30. </td>
  31. <td>
  32. <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
  33. </td>
  34. <td>
  35. <asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
  36. </td>
  37. </tr>
  38. <tr>
  39. <td>
  40. </td>
  41. <td>
  42. </td>
  43. <td>
  44. </td>
  45. <td>
  46. <asp:Button ID="AddProduct" runat="server" Style="color: White" Text="Add Product"
  47. OnClick="AddProduct_Click" BackColor="#999966" />
  48. </td>
  49. </tr>
  50. </table>
  51. <div style="margin-left:10px;margin-top:10px">
  52. <asp:GridView ID="GridView1" AutoGenerateColumns="false" runat="server" CellPadding="4"
  53. ForeColor="#333333" GridLines="None">
  54. <AlternatingRowStyle BackColor="White" />
  55. <Columns>
  56. <asp:BoundField HeaderStyle-Width="120px" HeaderText="Author Name" DataField="AuthorName" />
  57. <asp:BoundField HeaderStyle-Width="120px" HeaderText=" Book Name" DataField="BookName" />
  58. <asp:BoundField HeaderStyle-Width="120px" HeaderText=" Book Type" DataField="BookType" />
  59. <asp:BoundField HeaderStyle-Width="120px" HeaderText="Publisher" DataField="Publisher" />
  60. </Columns>
  61. <EditRowStyle BackColor="#2461BF" />
  62. <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
  63. <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
  64. <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
  65. <RowStyle BackColor="#EFF3FB" />
  66. <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
  67. <SortedAscendingCellStyle BackColor="#F5F7FB" />
  68. <SortedAscendingHeaderStyle BackColor="#6D95E1" />
  69. <SortedDescendingCellStyle BackColor="#E9EBEF" />
  70. <SortedDescendingHeaderStyle BackColor="#4870BE" />
  71. </asp:GridView>
  72. </div>
  73. </form>
  74. </body>
  75. </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. if (dtCurrentTable.Rows.Count > 0)
  10. {
  11. for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
  12. {
  13. //add each row into data table
  14. drCurrentRow = dtCurrentTable.NewRow();
  15. drCurrentRow["AuthorName"] = TextBox1.Text;
  16. drCurrentRow["BrandName"] = TextBox2.Text;
  17. drCurrentRow["Warrenty"] =TextBox3.Text;
  18. drCurrentRow["Price"] =TextBox4.Text;
  19. }
  20. //Remove initial blank row
  21. if (dtCurrentTable.Rows[0][0].ToString() == "")
  22. {
  23. dtCurrentTable.Rows[0].Delete();
  24. dtCurrentTable.AcceptChanges();
  25. }
  26. //add created Rows into dataTable
  27. dtCurrentTable.Rows.Add(drCurrentRow);
  28. //Save Data table into view state after creating each row
  29. ViewState["AuthorBooks"] = dtCurrentTable;
  30. //Bind Gridview with latest Row
  31. GridView1.DataSource = dtCurrentTable;
  32. GridView1.DataBind();
  33. }
  34. }
  35. }
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. protected void Page_Load(object sender, EventArgs e)
  6. {
  7. if (!IsPostBack)
  8. {
  9. AddDefaultFirstRecord();
  10. }
  11. }
  12. protected void AddProduct_Click(object sender, EventArgs e)
  13. {
  14. AddNewRecordRowToGrid();
  15. }
  16. private void AddDefaultFirstRecord()
  17. {
  18. //creating dataTable
  19. DataTable dt = new DataTable();
  20. DataRow dr;
  21. dt.TableName = "AuthorBooks";
  22. dt.Columns.Add(new DataColumn("AuthorName", typeof(string)));
  23. dt.Columns.Add(new DataColumn("BookName", typeof(string)));
  24. dt.Columns.Add(new DataColumn("BookType", typeof(string)));
  25. dt.Columns.Add(new DataColumn("Publisher", typeof(string)));
  26. dr = dt.NewRow();
  27. dt.Rows.Add(dr);
  28. //saving databale into viewstate
  29. ViewState["AuthorBooks"] = dt;
  30. //bind Gridview
  31. GridView1.DataSource = dt;
  32. GridView1.DataBind();
  33. }
  34. private void AddNewRecordRowToGrid()
  35. {
  36. // check view state is not null
  37. if (ViewState["AuthorBooks"] != null)
  38. {
  39. //get datatable from view state
  40. DataTable dtCurrentTable = (DataTable)ViewState["AuthorBooks"];
  41. DataRow drCurrentRow = null;
  42. if (dtCurrentTable.Rows.Count > 0)
  43. {
  44. for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
  45. {
  46. //add each row into data table
  47. drCurrentRow = dtCurrentTable.NewRow();
  48. drCurrentRow["AuthorName"] = TextBox1.Text;
  49. drCurrentRow["BookName"] = TextBox2.Text;
  50. drCurrentRow["BookType"] =TextBox3.Text;
  51. drCurrentRow["Publisher"] =TextBox4.Text;
  52. }
  53. //Remove initial blank row
  54. if (dtCurrentTable.Rows[0][0].ToString() == "")
  55. {
  56. dtCurrentTable.Rows[0].Delete();
  57. dtCurrentTable.AcceptChanges();
  58. }
  59. //add created Rows into dataTable
  60. dtCurrentTable.Rows.Add(drCurrentRow);
  61. //Save Data table into view state after creating each row
  62. ViewState["AuthorBooks"] = dtCurrentTable;
  63. //Bind Gridview with latest Row
  64. GridView1.DataSource = dtCurrentTable;
  65. GridView1.DataBind();
  66. }
  67. }
  68. }
  69. }
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.