Programmatically add Click EventHandler to Button - c#

I'm creating Buttons programmatically with a method and am wanting to attach a Click event handler. However, that data currently comes from a string parameter which can't be used with += RoutedEventHandler.
public Button CreateButton(string Display, string Name, string ClickEventHandler)
{
Button Btn = new Button
{
Content = Display,
Name = "Btn_" + Name
};
Btn.Click += new RoutedEventHandler(ClickEventHandler);
return Btn;
}
void Btn_save_Click(object sender, RoutedEventArgs e)
{
throw new NotImplementedException();
}
// later
Button MyButton = CreateButton("Save", "save", "Btn_save_Click");
Error is RoutedEventHandler expects a Method and not a String. Is there a different approach to programmatically binding events that allows this sort of behaviour?
Thanks

From what I understand you wish to pass the method that should be executed when Click event is triggered. You could do something along the lines of:
Button button = CreateButton("Save", "save", (s, e) => SomeOnClickEvent(s, e));
Button button2 = CreateButton("Create", "create", (s, e) => SomeOtherOnClickEvent(s, e));
public Button CreateButton(string display, string name, Action<object, EventArgs> click)
{
Button b = new Button()
{
Content = display,
Name = $"Btn_{name}"
};
b.Click += new EventHandler(click);
return b;
}
void SomeOnClickEvent(object sender, EventArgs e)
{
}
void SomeOtherOnClickEvent(object sender, EventArgs e)
{
}

I am not entirely sure what you are trying to accomplish with this.
Here is an example of how to create an event at run time.
public void CreateButton()
{
Button Btn = new Button();
Btn.Click += new EventHandler(btn_Clicked);
}
private void btn_Clicked(object sender, EventArgs e)
{
// Your Logic here
}

Related

add keyup event for dynamically generated buttons in c#

I'm trying to define a keyUp event for a List of buttons that I generate dynamically but I can't find the appropriate method to do it.
This is the code that I use to generate the buttons.
public void generateurBtns()
{
test.cmd.CommandText = "select id from Citoyens";
test.cmd.Connection = test.cnx;
test.dr = test.cmd.ExecuteReader();
while (test.dr.Read())
{
Button Citoyen = new Button();
citoyensBtns.Add(Citoyen);
this.Controls.Add(Citoyen);
Citoyen.Name = test.dr[0].ToString();
Citoyen.Click += new EventHandler(button_keyup);
}
test.dr.Close();
}
I defined the button_keyup method as following.
void button_keyup(object sender, EventArgs e)
{
//code executed if button released
}
Any suggestions on how to make this work?
Hav you tried KeyUp event instead of Click ?
public void generateurBtns()
{
test.cmd.CommandText = "select id from Citoyens";
test.cmd.Connection = test.cnx;
test.dr = test.cmd.ExecuteReader();
while (test.dr.Read())
{
Button Citoyen = new Button();
citoyensBtns.Add(Citoyen);
this.Controls.Add(Citoyen);
Citoyen.Name = test.dr[0].ToString();
Citoyen.KeyUp += new KeyEventHandler(button_keyup);
}
test.dr.Close();
}
update : you will also need to implement the right delegate:
void button_keyup(object? sender, KeyEventArgs e)
{
//code executed if button released
}

Optimizing a repetiton

I have a small Menu strip item where I have a plethora of buttons which activate different forms.
The code for one button would be this:
Form B1 = new Form1();
private void Button1_Click(object sender, EventArgs e)
{
if (B1.Visible == false)
{
B1 = new Form1();
}
B1.Visible = true;
B1.Activate();
}
I also have a mouse enter- and leave event:
private void Button1_MouseEnter(object sender, EventArgs e)
{
Button1.Text = "Something prdy intriguing";
}
private void Button1_MouseLeave(object sender, EventArgs e)
{
Button1.Text = "Hi";
}
And a tooltip:
private void Tooltips()
{
ToolTip forB1 = new ToolTip();
forB1.SetToolTip(button1, "21.11.17");
}
Now imagine i need about 8 buttons for 8 different forms, that means i have to repeat all of these again and a gain, wasting time AND taking up a LOT of code space.
Is it possible to compress these in anyway?
This is very out of my world, im unsure where to start optimizing.
One option is move all this to one function:
public void AttachMenuStripButtonHandlers(
Button btn,
Form form,
string enterText,
string leaveText,
string tooltip) {
btn.Click += (sender, args) => {
form.Visible = true;
form.Activate();
};
btn.MouseEnter += (sender, args) => {
btn.Text = enterText;
};
btn.MouseLeave += (sender, args) => {
btn.Text = leaveText;
};
new ToolTip().SetToolTip(btn, tooltip);
}
And for each button call like this:
AttachMenuStripButtonHandlers(Button1, B1, "on enter", "on leave", "tooltip");
For second part of your question, You could do something like this
private void Button_MouseEnter(object sender, EventArgs e)
{
((Button)sender).Text = "Something prdy intriguing";
}
private void Button_MouseLeave(object sender, EventArgs e)
{
((Button)sender).Text = "Hi";
}
You need to attach same event handler to all buttons.
So i am kinda stealing #Evk's code here but essentially this works the way I wanted to.
public void ButtonHandlers(Type NewForm)
{
NewButton.Click += (sender, args) =>
{
Form TheNewMain = (Form)Activator.CreateInstance(NewForm);
if (TheNewMain.ShowDialog() != DialogResult.Cancel)
{
TheNewMain.Activate();
}
};
Essentially what i added was instead of getting the Form i have to get the type, since what I want is that when a form is Visible, it won't open it twice, going by Evks code it opens it yes but upon close it's disposed and it cant create a new instance of it.
In code i just have to ask for typeof(formName) in as NewForm
Thanks Evk!

Pass variable with onclick method in asp.net

I create a button dynamically and I want when my button click and onclick event fired, a variable pass with this event.
Button btn = new Button();
btn.Click += new EventHandler(Button_Click);
//btn.Click += new EventHandler(Button_Click(32)); <-- I want something like this
divUserUploadedList.Controls.Add(btn);
And this is Onclick event:
protected void Button_Click(object sender, EventArgs e)
{
//I want to access that value here
}
You can do this by using CommandArgument property
protected void Page_Load(object sender, EventArgs e)
{
Button btn = new Button();
btn.Click += btn_Click;
btn.CommandArgument = "12"; //<-- you can pass argument like this
divUserUploadedList.Controls.Add(btn);
}
void btn_Click(object sender, EventArgs e)
{
Button btn = sender as Button;
string value = btn.CommandArgument;
}
What you are looking for is probably the CommandArgument property.
https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.commandargument%28v=vs.110%29.aspx

Adding button events!

I add buttons dynamically.. e.g. Button newButton=new Button();
Now i want each button to be triggered. So i wrote them the following events:
public void response_Click(object sender, EventArgs e)
{
}
public void edit_Click(object sender, EventArgs e)
{
}
public void quote_Click(object sender, EventArgs e)
{
}
Button quote = new Button();
Button reply = new Button();
Button edit = new Button();
quote.ID = "quote";
reply.ID = "reply";
edit.ID = "edit";
How do i trigger them, as soon as the user clicks on the button..will my functions above be triggered? do i need to do the following:
this.Clicked+=quote;
this.Clicked+=reply;
this.Clicked+=edit;
if i do need to do that..where do i put those lines of code?
i use visual studio 1010. asp.net
You can do like..
quote.Click += new EventHandler(quote_Click);
reply.Click += new EventHandler(response_Click);
edit.Click += new EventHandler(edit_Click);
Yes, you would need to register the event of the button and associate it with particular method.
for example.
myButton.Click += new EventHandler(Button_Click);
void Button_Click(object sender, EventArgs e)
{
}

How can I create a dynamic button click event on a dynamic button?

I am creating one button on a page dynamically. Now I want to use the button click event on that button.
How can I do this in C# ASP.NET?
Button button = new Button();
button.Click += (s,e) => { your code; };
//button.Click += new EventHandler(button_Click);
container.Controls.Add(button);
//protected void button_Click (object sender, EventArgs e) { }
The easier one for newbies:
Button button = new Button();
button.Click += new EventHandler(button_Click);
protected void button_Click (object sender, EventArgs e)
{
Button button = sender as Button;
// identify which button was clicked and perform necessary actions
}
Simply add the eventhandler to the button when creating it.
button.Click += new EventHandler(this.button_Click);
void button_Click(object sender, System.EventArgs e)
{
//your stuff...
}
It is much easier to do:
Button button = new Button();
button.Click += delegate
{
// Your code
};
You can create button in a simple way, such as:
Button button = new Button();
button.Click += new EventHandler(button_Click);
protected void button_Click (object sender, EventArgs e)
{
Button button = sender as Button;
// identify which button was clicked and perform necessary actions
}
But event probably will not fire, because the element/elements must be recreated at every postback or you will lose the event handler.
I tried this solution that verify that ViewState is already Generated and recreate elements at every postback,
for example, imagine you create your button on an event click:
protected void Button_Click(object sender, EventArgs e)
{
if (Convert.ToString(ViewState["Generated"]) != "true")
{
CreateDynamicElements();
}
}
on postback, for example on page load, you should do this:
protected void Page_Load(object sender, EventArgs e)
{
if (Convert.ToString(ViewState["Generated"]) == "true") {
CreateDynamicElements();
}
}
In CreateDynamicElements() you can put all the elements you need, such as your button.
This worked very well for me.
public void CreateDynamicElements(){
Button button = new Button();
button.Click += new EventHandler(button_Click);
}
Let's say you have 25 objects and want one process to handle any one objects click event. You could write 25 delegates or use a loop to handle the click event.
public form1()
{
foreach (Panel pl in Container.Components)
{
pl.Click += Panel_Click;
}
}
private void Panel_Click(object sender, EventArgs e)
{
// Process the panel clicks here
int index = Panels.FindIndex(a => a == sender);
...
}

Categories

Resources