CodeBetter.Com
CodeBetter.Com
RSS 2.0 via Feedburner
           Do you Twitter? Follow us @CodeBetter

Peter's Gekko

public Blog MyNotepad : Imho { }

Viewstate (hog) and the datagrid

Sometime ago I had been wrestling through the viewstate and blogged on it. On a page with a datagrid the viewstate can be enormous. As the viewstate travels over the wire on every roundtrip this can be quite a problem in a situation where the bandwidth is limited. A lot of data in a datagrid is reread on every roundtrip, having it also in the viewstate is quite a waste. But some of the properties of a datagrid, like the selectedindex have to be preserved over the roundtrips. The viewstate can be disabled on a control basis. Which will also disable the viewstate of all controls owned by the control. Disabling it on a datagrid will also disable it for the controls in a template column. Disabling it on the page will disable it for all controls on the page.

The problem with the viewstate of the datagrid is that you need it for some integers and end up with one which stores an entire grid. In a comment on the old post Simon asks if there is an easy way out of this. Something like the Whideby solution where you can disable the viewstate but preserve the main properties like SelectedIndex. There is, it takes some lines of code.

Disable the viewstate of  the datagrid (and other controls), but do not disable the viewstate of the page itself. You use the latter to save your properties over roundtrips. Something like this :

const string mySelIndex = "MySelIndex";
private int mySelectedIndex
{
   get
   {
      if (this.ViewState[mySelIndex] == null)
         return -1;
      else
         return (int)this.ViewState[mySelIndex];
   }
   set
  {
      this.ViewState[mySelIndex] = value;
   }
}

...

private void Page_Load(object sender, System.EventArgs e)
{
   // Read data here
   DataGrid1.DataBind();
   DataGrid1.SelectedIndex = this.mySelectedIndex;
}

private void WebForm1_PreRender(object sender, System.EventArgs e)
{
   this.mySelectedIndex = DataGrid1.SelectedIndex;
}

The page has a new private property mySelectedInded. Which uses the viewstate of the page itself to store the index. In the page load the index is read, in the page prerender it is saved. The page still does have a viewstate but you will see that it is very very small. Get the idea ?

Peter


Published Dec 15 2004, 01:25 PM by pvanooijen
Filed under:

Check out Devlicio.us!

This Blog

Syndication

News