How to create and call dynamically instantiated methods in C#? [duplicate] - c#

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);
...
}

Related

How to put new eventhandle on existing buttons c#?

I want to put on existing button new event handle. I have 9 buttons created in form and want to display each name when is clicked on it, but don't want to put on every button message manually.
How to accomplish that?
You can use the sender propperty of the EventHandler in order to do that. This example uses winforms buttons:
SomeButtonClicked(object sender, EventArgs e)
{
var button = sender as Button;
MessageBox.Show(button.Name);
}
And then you can add this event to multiple buttons i.e.:
button1.Click += new System.EventHandler(SomeButtonClicked);
button2.Click += new System.EventHandler(SomeButtonClicked);
button3.Click += new System.EventHandler(SomeButtonClicked);
You can code something like this
private void MainForm_Load(object sender, EventArgs e) {
...
// Assigning on click event, assuming that all your buttons are on the MainForm
foreach (Control ctrl in Controls) {
Button btn = ctrl as Button;
if (!Object.ReferenceEquals(null, btn))
btn.Click += onButtonClick;
}
...
// On click itself
private void onButtonClick(Object sender, EventArgs e) {
Button btn = sender as Button;
String name = btn.Name; // <- Or whichever property of the button you want
}

How to Use Dynamically Created Button/textBox in C# Windows Forms?

private void createButton()
{
flowLayoutPanel1.Controls.Clear();
for (int i = 0; i < 4; i++)
{
Button b = new Button();
b.Name = i.ToString();
b.Text = "Button" + i.ToString();
flowLayoutPanel1.Controls.Add(b);
}
}
private void button1_Click(object sender, EventArgs e)
{
createButton();
}
I Used this code to create some buttons on runtime , now how can i use those created buttons to perform diffrent actions? Im kindz new to this so please help me , very much appreciated :)
You can assign an event handler to the click event:
b.Click += SomeMethod;
SomeMethod must have the following signature:
void SomeMethod(object sender, EventArgs e)
b.Click += delegate(object sender, EventArgs e) {
Button clickedButton = (Button)sender; //gets the clicked button
});
When you create your button, you need to subscribe to the Click event like this :
Button b = new Button();
b.Click += new EventHandler(b_Click);
// or
b.Click += b_Click;
// or
b.Click += delegate(object sender, EventArgs e) {/* any action */});
// or
b.Click += (s, e) => { /* any action */ };
void b_Click(object sender, EventArgs e)
{
// any action
}
This is something that is automatically done when your are is the designer in Visual Studio, and you click on a button to create the method button1_Click.
You can search in the Designer.cs of your form, you will find an equivalent line:
button1.Click += new EventHandler(button1_Click);
Related question:
How can i create dynamic button click event on dynamic button

how to create events on dynamic `textboxes`

I managed to create textboxes that are created at runtime on every button click. I want the text from textboxes to disappear when I click on them. I know how to create events, but not for dynamically created textboxes.
How would I wire this up to my new textboxes?
private void buttonClear_Text(object sender, EventArgs e)
{
myText.Text = "";
}
This is how you assign the event handler for every newly created textbox :
myTextbox.Click += new System.EventHandler(buttonClear_Text);
The sender parameter here should be the textbox which sent the even you will need to cast it to the correct control type and set the text as normal
if (sender is TextBox) {
((TextBox)sender).Text = "";
}
To register the event to the textbox
myText.Click += new System.EventHandler(buttonClear_Text);
Your question isn't very clear, but I suspect you just need to use the sender parameter:
private void buttonClear_Text(object sender, EventArgs e)
{
TextBox textBox = (TextBox) sender;
textBox.Text = "";
}
(The name of the method isn't particularly clear here, but as the question isn't either, I wasn't able to suggest a better one...)
when you create the textBoxObj:
RoutedEventHandler reh = new RoutedEventHandler(buttonClear_Text);
textBoxObj.Click += reh;
and I think (not 100% sure) you have to change the listener to
private void buttonClear_Text(object sender, RoutedEventArgs e)
{
...
}
I guess the OP wants to clear all the text from the created textBoxes
private void buttonClear_Text(object sender, EventArgs e)
{
ClearSpace(this);
}
public static void ClearSpace(Control control)
{
foreach (var c in control.Controls.OfType<TextBox>())
{
(c).Clear();
if (c.HasChildren)
ClearSpace(c);
}
}
This should do the job :
private void button2_Click(object sender, EventArgs e)
{
Button btn = new Button();
this.Controls.Add(btn);
// adtionally set the button location & position
//register the click handler
btn.Click += OnClickOfDynamicButton;
}
private void OnClickOfDynamicButton(object sender, EventArgs eventArgs)
{
//since you dont not need to know which of the created button is click, you just need the text to be ""
((Button) sender).Text = string.Empty;
}

How can i take dynamically created buttons' name when they are clicked?

I'm making a mahjong game and I'm totally new at C#, I wonder how i can take a button's name when it's clicked. All the buttons are created dynamically in the form.
public Button createButton(node x)
{
Button nButton;
nButton = new Button();
nButton.Name = x.info.ToString();
nButton.Text = x.info.ToString();
nButton.Width = 55;
nButton.Height = 75;
nButton.Visible = true;
if (x.isValid())
nButton.Enabled = true;
else
nButton.Enabled = false;
nButton.Click += new System.EventHandler(n1_click);
return nButton;
}
in the form i take buttons with this code
myButton = createButton(tp);
myButton.Location = new System.Drawing.Point(25 , 25);
this.Controls.Add(myButton);
The first argument to the event handler is the sender, you can cast that to a Button and then access the Name property.
Here is a small example of the event handler.
private void Button_Click(object sender, EventArgs e)
{
Button button = sender as Button;
if (button != null)
{
// Do something with button.Name
}
}
Edit: As Hans mentioned in the comments, using as could hide a potential bug. Using the as operator as in the example above will ensure that if you inadvertently wire this handler to an event of another control the code will handle it graciously and not throw an InvalidCastException, but there-in lies a problem as well, because this now silently fails you might not pickup a bug in your code. If the exception was thrown you would have realized there is a problem and been able to track it down. So the updated code would be something like this.
private void Button_Click(object sender, EventArgs e)
{
// If sender is not a Button this will raise an exception
Button button = (Button)sender;
// Do something with button.Name
}
With the following code you can get the button that was clicked
protected void Button1_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
}
on the function which handles the click "n1_click"
private void n1_click(object sender, EventArgs e)
{
Button temp = (Button)sender;
string neededText = temp.Text;
}

How do I identify which control generated the Click event?

In the following code, how do I identify which control raised the Click event?
void x_Click(object sender, EventArgs e)
{
//How do I identify the sender?
}
private void fill()
{
for(blah)
{
Button x = new Button();
x.Click += new EventHandler(x_Click);
this.controls.Add(x)
}
}
void x_Click(object sender, EventArgs e)
{
Button who = (Button) sender;
// you can now access who.Text, etc.
}

Categories