How to add event to dynamic control (button) asp.net

{0 Comments}

When there is need to assign a event to an dynamically created button and controls. Then we can use Command Argument associated with that control. The value assigned to this command argument is passed to an event handler which will work in similar manner in which your default static button works.

To understand this process I have created a dynamic button on page load event which will add a button with basic properties like ID, name, Tool tip,.  Then add a text box which static (drag and drop) whose text is used to pass to command argument.

                Then after create event handler for the dynamic button. Then  same value is show in message box. 

page load:

 C# |  copy code |? 
01
 protected void Page_Load(object sender, EventArgs e)
02
    {
03
        Button b = new Button();
04
        b.ID = "new"; 
05
        b.Text = "submit";
06
        b.ToolTip = "submit";
07
        b.CommandArgument = TextBox1.Text; //passing this to event handler
08
        b.Command += new CommandEventHandler(b_Command); //handler
09
        form1.Controls.Add(b);
10
 
11
    }

event handler

 C# |  copy code |? 
1
void b_Command(object sender, CommandEventArgs e)
2
    {
3
        System.Windows.Forms.MessageBox.Show(e.CommandArgument.ToString());
4
    }

Leave a Comment

Your email address will not be published.