Click here to Skip to main content
15,908,581 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hello,
I am attempting to bind an event to a variable numbr of dynamically created <asp:button> elements a table. Here is my code :-


C#
// where src = a hashtable of dataObject objects
foreach (dataObject srcobj in src.Values){
   TableRow row = new TableRow();
   TableCell srcname = new TableCell();
   Button nameBtn = new Button();
   nameBtn.Command += new CommandEventHandler(this.nameBtn_Click);
   nameBtn.CommandName = "graphClick";
   nameBtn.CommandArgument = srcobj.id.ToString();

// I have also tried this
   //nameBtn.Attributes.Add("OnCommand", "nameBtn_Click");
   //nameBtn.Attributes.Add("CommandArgument"", srcobj.id.ToString());
   //nameBtn.Attributes.Add("CommandName","name button click");

   nameBtn.ID = "data" + srcobj.id.ToString();
   nameBtn.Text = srcobj.name;
   srcname.Controls.Add(nameBtn);
   row.Cells.Add(srcname);
}
            
protected void nameBtn_Click(object sender, CommandEventArgs e)
        {
            string debug = e.CommandArgument.ToString();
        }


The problem I am having is that it seems as though the click event is never fired, the page posts back but doesn't hit my breakpoint within the click method.

what am I doing wrong?

Cheers
Gib
Posted

1 solution

Do you re-create the button at postback?
If not the event won't fire properly!
 
Share this answer
 
Comments
Gibb3h 31-Mar-11 10:03am    
oops, forgot about that, sorted now, thanks a lot :)
Keith Barrow 31-Mar-11 10:17am    
Easily Done!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900