Reputation: 522
I'm sure that almost everyone programming in .net has ran into similar issues with the dynamic creation of buttons..
Example scenario..
I have a gridview and in one of the gridview fields I have a button. Normally in .net using visual studio you can easily grab the click event of the button, however since these buttons are dynamically created they're not as easy to grab. I was curious to what the best method for grabbing the button's click event would be.
I understand its possible using dopostback; however, I'm not sure how to implement it nor have I tried because I have also read dopostback method is not a very good one to use. Why is that?
Upvotes: 0
Views: 343
Reputation: 522
Sadly, the answer was much simpler than I ever thought..
I didn't realize that the ItemCommand event was usable for buttons created in a TemplateField.
All I really had to do was..
Private Sub GridView1_ItemCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DetailsViewCommandEventArgs) Handles DetailsView1.ItemCommand
If e.CommandName = "myButton" Then
//'myButton press event logic here
End If
End Sub
Thanks for your help guys.. I really appreciate it. Your answers will be helpful in the future I'm sure.
Upvotes: 1
Reputation: 101330
In the gridview, there is an event called RowDatabound. Put an event handler on that:
gv.RowDataBound += new EventHandler(rowBound);
Now inside that function, you'll use FindControl to locate the button and add a handler:
function rowbound(Object sender, GridViewRowEventArgs e) { if(e.Row.RowType == DataControlRowType.DataRow) { var b = e.Row.FindControl("btn") as Button; b.Click += new EventHandler(handleBtnClick); } }
Upvotes: 4
Reputation: 59165
During the ItemCreated event of the Gridview use FindControl to get a reference to the button and attach the event handler there. ie. btn.Click += Somehandler;
Upvotes: 2