Be sure to access the page at the correct time. If you access it in the OnInit event, the ViewState will not have been mapped back on your grid.
PageLoad would be appropriate probably.
If you want to retrieve 'orderid' in more clean way, you can use CommandName
, CommandArgument
properties and OnRowCommand
event like this:
<asp:GridView (...) OnRowCommand="Gv_RowCommand" (...)>
...
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="Select"
CommandArgument='<%# Bind("orderId") %>' Text="Button"></asp:LinkButton>
and in code behind:
protected void Gv_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
int selectedOrderId = Convert.ToInt32(e.CommandArgument);
// ...
}
}
I hope this is what you want to do.
Edit - my answer to your comment:
Then, it's little more complicated and uses 'selectedRow' in some way. In my own code, I use this approach:
<asp:GridView ID="gv1" (...) DataKeyNames="orderId,email,username"
OnRowCommand="Gv_RowCommand" (...)>
...
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="Select"
CommandArgument='<%# DataBinder.Eval(Container,"RowIndex") %>' Text="Button">
</asp:LinkButton>
and in code behind:
protected void Gv_RowCommand(object sender, GridViewCommandEventArgs e)
{
int selectedRowIndex = Convert.ToInt32(e.CommandArgument);
if (e.CommandName == "Select")
{
int orderId = Convert.ToInt32(gv1.DataKeys[selectedRowIndex]["orderId"]);
string email = gv1.DataKeys[selectedRowIndex]["email"].ToString();
// ...
}
}
Best Answer
This is probably caused by when you're creating the dynamic column.
If the column is created in the Page_Load event, or later in the page event process, then ViewState will not be able to populate your columns on a PostBack.
If possible, try creating your dynamic columns in the Page_Init event. This will allow ViewState to load the columns properly.