2014年7月13日 星期日

[RESOLVED] Dynamically created LinkButton's Click event is not firing in RowCommand of GridView


Hi,


I create a linkbutton in RowDataBound event of GridView, and try to access that link button's click event in RowCommand Event of GridView.


But, LinkButton's click event is not getting fired. How to achieve this?


My code looks below:

----------------------

protected void gridPlacement_RowDataBound(object sender, GridViewRowEventArgs e)

{

if (e.Row.RowType == DataControlRowType.DataRow)

{

lnkCount = new LinkButton();

lnkCount.ID = "lnk_";

lnkCount.CommandName = "GET_STUDENTS";

lnkCount.CommandArgument = "1";

lnkCount.Text = e.Row.Cells[0].Text;

e.Row.Cells[0].Controls.Add(lnkCount);

}

}


protected void gridPlacement_RowCommand(object sender, GridViewCommandEventArgs e)

{


if(e.CommandName=="GET_STUDENTS")


{


Label1.Text=e.CommandArgument.toString();


}


}



The problem is probably in the code you're not showing.  When you bind a function to an event, you have to do it whether it is a postback or not.  This can be done by defining the event in the control's mark-up on the aspx page, or if you are attaching the
event in your code-behind make sure it is not inside an "if (!Page.IsPostback)" block..


 


Edit: make sure your grid is always being bound, not just on no postback.



Link button is dynamically created. How will change in html view? 



If your button is created dynamically then you have to ensure its events are added each time, even if it is a postback.  The easiest way of making sure this happens is to always bind your data grid (or whatever it is), even on postback.  It's a trade-off
of performance vs network bandwidth, but it means you don't have to worry about hooking your events back up.


Buttons don't get their event handlers assigned automatically, you *have* to assign them yourself with every page load as they are not persisted across page-loads.



in page_load event, rebind the gridview again.... you can set a viewstate or session flag from rowdatabound event.... and based on that flag, rebind the grid on next postback in page_load event


this will regenrate the linkbutton and if control object is available, it will be able to invoke its click event


hope this helps...


沒有留言:

張貼留言