views:

174

answers:

3

Hello everyone,

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?

+5  A: 

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);
  }
}
Tom Ritter
I think goodwince is asking how to set an event handler to a dynamically created control inside a gridview. cmsjr's answer seems to fit better.
Kyle Trauberman
you're right. i fixed it
Tom Ritter
+2  A: 

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;

cmsjr
+1  A: 

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.

goodwince