Reputation: 2256
By following this post I have reduced the size of my ViewState up to 5 times less than when I was using the GridView with the full ViewState.
Basically, this is the code for optimizing the ViewState:
public void DisableViewState(GridView dg)
{
foreach (GridViewRow gvr in dg.Rows)
{
gvr.EnableViewState = false;
}
}
private void Page_Load(object sender, System.EventArgs e)
{
if (!Page.IsPostBack)
{
GridView1.DataSource = GetData();
GridView1.DataBind();
DisableViewState(GridView1);
}
}
By doing that, I am still able to use the sorting and paging functionalities of the GridView.
However, when using links inside the GridView, it does not behave as it did when it had the full ViewState, since the server code is not getting any value as CommandArgument. The following are the codes for the LinkButton and its event handler:
<ItemTemplate>
<asp:LinkButton CommandArgument='<%#Eval("idnumber")%>' ID="linkSelect" Text="Select"
runat="server" OnCommand="selectCommand"></asp:LinkButton>
</ItemTemplate>
Codebehind:
protected void selectCommand(object sender, CommandEventArgs e)
{
int numberID = int.Parse(e.CommandArgument.ToString());
selectCommandInfo(numberID);
}
Therefore, I am getting the error in the server side because it is trying to parse an empty string to int.
So, how can I optimize the ViewState when using GridViews with LinkButtons and their event handlers? Is there any other way to get the CommandArgument value in the codebehind?
Any help will be greatly appreciated.
Upvotes: 4
Views: 3338
Reputation: 445
One simple solution is to go one level deeper - disable ViewState
for cells instead of rows:
private void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType != DataControlRowType.DataRow)
return;
foreach (TableCell cell in e.Row.Cells)
cell.EnableViewState = false;
e.Row.Cells[0].EnableViewState = true;
e.Row.Cells[1].EnableViewState = true;
}
Assuming 0 and 1 are cells containing your LinkButton
and idnumber
.
Upvotes: 3
Reputation: 2433
I've seen this a couple of times during the last few months when developing in ASP. What I do sometimes is have a hidden text field on the page, which has viewstate enabled, then I have a control (Javascript) that sets the value of the hidden text field when selecting the link, I can then access the value from code behind. Trade off is you don't have to carry the GridView in Viewstate, but then you make the page a little messier with the hidden field and JS.
Best of luck
Upvotes: 2