[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 340
  • Last Modified:

Dynamic Buttons and Events

Hi,

I have decalre a Button object in the form without actually droping the control onto the form.
At run time i decide whether or not to add the button.

How can i write an event handler for this button?
0
cossy74
Asked:
cossy74
1 Solution
 
TheAvengerCommented:
Example: if you new button is btn and you want to handle Click, then:

btn.Click += new EventHandler (MyMethod);

where MyMethod has the standard for button click event handlers definition:

private void MyMethod (object sender, EventArgs e)
{
  // Do something
}
0
 
Fahad MukhtarDistinguished EngineerCommented:
I dont have VS.Net Right now but you can try this code:

Button DynamicButton1= new Button();
b.Name="DynamicButton1"+counterint
Controls.Add(DynamicButton1);
DynamicButton1.Click+=new System.EventHandler(this.DynamicButton1_Clicked); // change your function name here

and put your DynamicButton1_Clicked somewhere in the same class
0
 
JarodtweissCommented:
To complete the comments :
VB.NET syntax :

dim myButton as new Button
AddHandler myButton.Click, AddressOf me.Button_Click

if you want later to remove your handler :
RemoveHandler myButton.Click, AddressOf me.Button_Click

private sub Button_Click(sender as object, e as EventArgs)
end Sub
0
 
JarodtweissCommented:
Oops... Forget it...
I haven't seen I was surfing the C# section... :">
0
 
msdixonCommented:
you could always drag a new button on the form, then set the Visible property to false, and add your event handler... then, if you need the button, set the Visible property to true
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now