I have seen 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:
- "Start" - "All Programs" - "Microsoft Visual Studio".
- "File" - "New WebSite" - "C#" - "Empty WebSite" (to avoid adding a master page).
- Provide the web site a name such as "SaveDataTableInViewsate" or another as you wish and specify the location.
- Then right-click on Solution Explorer - "Add New Item" - Add Web Form.
- Drag and drop one button and three textBoxes onto the <form> section of the Default.aspx page.
- Now the default.aspx page source code will look such as follows.
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:
Now call the above function at Page Load so that the initial records will be added into the view state and GridView as
Now create a method 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:
Call the function above to add book details in the button click as:
Now the entire code of the default.aspx.cs page will be such as follows:
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 data table capacity.
- Do proper validation such as date input values when implementing.
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 drop in the comment box.
Don't forget to subscribe to my blog and YouTube channel