How to optimize the ViewState generated by the GridView and save some GridView related functions

Following this post , I reduced the size of my ViewState to 5 times smaller than when I used GridView with a full ViewState.

Basically, this is the code for optimizing 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); } } 

That way, I can still use the sort and swap functions in the GridView.

However, when using links inside a GridView, it does not behave as if it had a full ViewState, since the server code does not get any value as a CommandArgument. The following are the LinkButton and event handler codes:

 <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 get an error on the server side because it is trying to parse an empty string for int.

So, how can I optimize ViewState when using GridViews with LinkButtons and their event handlers? Is there any other way to get the value of CommandArgument in the code?

Any help would be greatly appreciated.

+4
source share
2 answers

I have seen this several times in the last few months when I was developing ASP. What I sometimes do has a hidden text field on the page where viewstate is enabled, then I have a control (Javascript) that sets the value of the hidden text field when selecting a link, then I can access the value from the code, Transaction - you do not need to transfer the GridView to the ViewState, but then you make the page a little messier with a hidden field and JS.

Good luck

+1
source

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 .

+2
source

Source: https://habr.com/ru/post/1391618/


All Articles