This is happening because the OnRowDataBound
event of GridView is NOT called on next postback. This happens because by default viewstate of GridView is set true i.e. EnableViewState
property of Gridview is true
. When ViewState is on, Gridview stores data from the same and OnRowDataBound
event is not called. Also, at this point View state will not be applied for your linkButtons
as they aren't created in page_load
.
Try setting EnableViewState
property to false for your gridview:
<asp:GridView ID="CustomersGridView"
OnRowDataBound="CustomersGridView_RowDataBound"
EnableViewState="false"
.... />
OR you can also bind your GridView
in page_Load
as:
protected void Page_Load(object sender, EventArgs e)
{
CustomersGrIdView.DataBind();
}
Now after every postback your OnRowDataBound
event will be called and hence the LinkButtons
will be available everytime.
NOTE: Setting EnableViewState
property to false for gridview can be a bad practice to an extent, especially in scenarios of heavy data usages. Same goes for Binding gridview every time.
When using dynamic controls, they exist only until the next postback.ASP.NET will not re-create a dynamically added control. If you need to re-create a control next time too on postback, you should perform the control creation in the PageLoad
event handler.
This will give you benefit of using view state with your dynamic control. Even though view state is normally restored before the Page.Load
event, if you create a control in the handler for the PageLoad
event, ASP.NET will apply any view state information that it has after the PageLoad
event handler ends.