Friday, May 27, 2005

 

Maintaining Data with a DataGrid

In my program, I need to have a DataGrid display some data from the database and then let someone enter in the data or modify or delete the existing data. However, I don't want the changes to be made to the actual database until the user has completed all of their edits. Thus, each change in the DataGrid needs to be made to some local copy of the data, rather than the actual database. The problem is that the DataGrid control does not maintain its state over roundtrips to the server.

To solve this I just created a variable of the type DataSet. Initially, I read the information from the database into the DataSet variable and then bind the DataGrid to the DataSet. This makes the information show up in the DataGrid. Well, the DataSet is just a variable on the page and will be destroyed with the page. Thus, I have to save the DataSet variable in the ViewState of the page.

In Page_Load:
  • If IsPostBack is false (first page load), then go set up the DataSet either by grabbing actual data or just the schema from the actual database.
  • If IsPostBack is true, then I do MyDataSet = CType(ViewState("MyDataSet"), DataSet)
In Page_PreRender:
  1. Assume that all modifications to the MyDataSet variable have been made according to the OnClick or other events.
  2. Bind the data to the DataGrid: MyDataGrid.DataSource = MyDataSet and then MyDataGrid.DataBind()
  3. ViewState("MyDataSet") = MyDataSet
The problem with this approach is that the data is stored twice in the page sent to the user: once to display it in the table, and once encoded in the ViewState variable. Oh well.

This page is powered by Blogger. Isn't yours?