I want to attach an event to a button clicked generated at runtime. Till this point I've wrote the code, but can't pass the button's ID to the method. Here is my code
This code does not through any error, another problem is after the click event the controls get washed away. How to prevent this ?
protected void Button1_Click(object sender, EventArgs e)
{
int i = int.Parse(TextBox1.Text);
for (int x = 1; x <= i; x++)
{
Button b = new Button();
b.ID = "btn_" + x.ToString();
b.Text = "btn_" + x.ToString();
b.Click += new System.EventHandler(myEventHandler);
pnlHolder.Controls.Add(b);
}
}
private void myEventHandler(object sender, EventArgs e)
{
txtMain.Text = sender.ToString(); // I want to know which button was pressed
}
try,
txtMain.Text = (sender as Button).Name;
or
txtMain.Text = (sender as Button).Text;
Try this
private void myEventHandler(object sender, EventArgs e)
{
Button b = (Button) sender;
txtMain.Text = b.ID;
//
txtMain.Text = b.Text;
if(b.ID == "button1")
doThis();
else if(b.ID == "button2")
doThat();
}
Related
I have array of buttons, and array of labels:
Label[] labels = new Label[10];
Button[] but = new Button[10];
While clicking the other button I want to dynamically create new button and new label from the array, i also want the but[i] to change the tex of labels[i]:
private void button1_Click(object sender, EventArgs e)
{
labels[i] = new Label();
labels[i].Location = new System.Drawing.Point(0, 15+a);
labels[i].Parent = panel1;
labels[i].Text = "Sample text";
labels[i].Size = new System.Drawing.Size(155, 51);
labels[i].BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
a = labels[i].Height + labels[i].Top;
but[i] = new Button();
but[i].Text = "-";
but[i].Location = new System.Drawing.Point(0, labels[i].Height + labels[i].Top);
but[i].Parent = panel1;
but[i].Size = new System.Drawing.Size(155, 10);
but[i].Click += new System.EventHandler(but_Click);
i++;
}
private void but[i]_Click(object sender, EventArgs e)
{
labels[i].Text = "Changed Text";
}
But apparently I can't put an array in an event handler, how should I do it then?
One way to do this is to make your method return a handler instead of being a handler:
private EventHandler but_Click(int i)
{
return (s, e) => labels[i].Text = "Changed Text";
}
And use it like:
but[i].Click += but_Click(i);
Or do it inline:
but[i].Click += (s, ea) => labels[i].Text = "Changed Text";
What's happening in either of these is some compiler magic to capture the i variable. It's equivalent to this (which is also a valid, if verbose, way to do it):
class MyWrapper {
private int i;
public MyWrapper(int i) {
this.i = i;
}
public void TheHandler(object sender, EventArgs e) {
// TODO: capture the object that owns `labels` also, or this won't work.
labels[i].Text = "Changed Text";
}
}
//call with
but[i].Click += new EventHandler(new MyWrapper(i).TheHandler);
You could add the array index to the button as Tag property, and then pull it back out in but_Click.
So, add
but[i].Tag = i;
to the button creation. And then change the event handler:
private void but_Click(object sender, EventArgs e)
{
int buttonIndex = (int)((Button)sender).Tag;
labels[buttonIndex].Text = "Changed Text";
}
Or put the event handler inline:
but[i].Click += (s,e) => { label[i].Text = "Changed Text"; }
Or another option using the Tag property, add:
but[i].Tag = label[i];
...
private void but_Click(object sender, EventArgs e)
{
Label label = (Label)((Button)sender).Tag;
label.Text = "Changed Text";
}
Advantage of this approach is you're not relying on keeping arrays in synch after the initial creation of the controls.
I guess this is self-explaining:
public void SomeMehthod()
{
Button btn1 = new Button();
Button btn2 = new Button();
Button btn3 = new Button();
// Your button-array
Button[] btns = new Button[]
{
btn1,
btn2,
btn3
};
foreach(Button btn in btns)
{
// For each button setup the same method to fire on click
btn.Click += new EventHandler(ButtonClicked);
}
}
private void ButtonClicked(Object sender, EventArgs e)
{
// This will fire on any button from the array
// You can switch on the name, or location or anything else
switch((sender as Button).Name)
{
case "btn1":
// Do something
break;
case "btn2":
// Do something
break;
case "btn3":
// Do something
break;
}
}
Or if your array is accessible globaly:
Button[] btns = new Button[5];
Label[] lbls = new Label[5];
private void ButtonClicked(Object sender, EventArgs e)
{
Button clicked = sender as Button;
int indexOfButton = btns.ToList().IndexOf(clicked);
// ..IndexOf() returns -1 if nothign is found
if(indexOfButton > 0)
{
lbls[indexOfButton].DoWhatYouWant...
}
}
i tried to do this(mine field) but i cant visible = false any button when im clicked that.
by the way this.visible = false is going to visible form -.-
private void Form1_Load(object sender, EventArgs e)
{
this.Size = new Size(541, 537);
for (int j = 24; j < ClientSize.Height; j += 25)
{
for (int i = 0; i < ClientSize.Width; i += 25)
{
Button btn = new Button();
btn.Width = 25;
btn.Height = 25;
btn.Location = new Point(i, j);
btn.Click += btn_Click;
Controls.Add(btn);
}
}
}
void btn_Click(object sender, EventArgs e)
{
//When i clicked anyone of them that comes be invisible,
}
thx for helping
The control that fired the event is stored in sender - cast it back to a Button.
void btn_Click(object sender, EventArgs e)
{
var button = (Button)sender;
button.Hide();
}
Alternatively, if that's all you're doing in the event, you could define it in a single line like this:
btn.Click += delegate { btn.Hide(); };
I have 2 buttons in my win app.
Button1 do a task :
private void button1_Click(object sender, EventArgs e)
{
progressBar1.Value = 0;
String[] a = textBox7.Text.Split('#');
progressBar1.Maximum = a.Length;
for (var i = 0; i <= a.GetUpperBound(0); i++)
{
ansh.Close();
progressBar1.Value++;
}
}
Button 2 do following
private void button2_Click(object sender, EventArgs e)
{
foreach (string item in listBox2.Items)
textBox7.Text += item.Contains("#") ? string.Format("{0}#", item.Split('#')[0]) : string.Empty;
}
I just want to use just one button for two events.
But I want the event of button2 to be called before event that was called by button1.
Means I want to use just one button instead of button 1 and 2.and when I click I want first thing to be done is getting listbox items in a textbox.
{
foreach (string item in listBox2.Items)
textBox7.Text += item.Contains("#") ? string.Format("{0}#", item.Split('#')[0]) : string.Empty;
}
and then the event of starting progress bar and closing connection x.
progressBar1.Value = 0;
String[] a = textBox7.Text.Split('#');
progressBar1.Maximum = a.Length;
for (var i = 0; i <= a.GetUpperBound(0); i++)
{
ansh.Close();
progressBar1.Value++;
}
You can use PerformClick method of button object
Button button1 = new Button(), button2 = new Button();
button1.Click += new EventHandler(button1_Click);
button2.Click += new EventHandler(button2_Click);
void button1_Click(object sender, EventArgs e)
{
/* .................... */
button2.PerformClick(); //Simulate click on button2
/* .................... */
}
void button2_Click(object sender, EventArgs e)
{
/* .................... */
}
I'd suggest removing the logic from behind the click events into separate methods.
private void MethodOne()
{
progressBar1.Value = 0;
String[] a = textBox7.Text.Split('#');
progressBar1.Maximum = a.Length;
for (var i = 0; i <= a.GetUpperBound(0); i++)
{
ansh.Close();
progressBar1.Value++;
}
}
private void MethodTwo()
{
foreach (string item in listBox2.Items)
textBox7.Text += item.Contains("#") ? string.Format("{0}#", item.Split('#')[0]) : string.Empty;
}
private void button1_Click(object sender, EventArgs e)
{
MethodTwo();
MethodOne();
}
private void button2_Click(object sender, EventArgs e)
{
MethodTwo();
}
In my experience, it's easier to maintain and test this way. Having different controls' events all calling each other makes it tougher to follow the logic.
You can trigger the click event of Button2 manually:
private void button1_Click(object sender, EventArgs e)
{
button2_Click(sender,e);
...
}
Just in case you neen events:
Button1.click += method1;
Button1.click += method2;
void method1(object sender, EventArgs e)
{
// do your stuff
}
void method2(object sender, EventArgs e)
{
// do your stuff
}
I have created a number of silverlight buttons thus:-
string b = "Button";
for (int i = 0; i < 10; i++)
{
Button btn = new Button();
btn.Name = b+i.ToString();
btn.FontSize += 2;
btn.Content = "Click Me " ;
btn.Click += new RoutedEventHandler(btn_Click);
stack.Children.Add(btn);
}
LayoutRoot.Children.Add(stack);
In the button click event I want to get the name of the button that was pressed. I had hoped that
string snd = sender.ToString(); would yield the information but all it gives is System.Windows.Controls.Button. Can anyone please help. Thanks.
You need to cast sender to a button.
public void btn_Click(object sender, EventArgs e)
{
var btn = (Button)sender;
Console.WriteLine(btn.Name);
}
public void btn_Click(object sender, EventArgs e)
{
var b = sender as Button;
if (b != null)
{
var name = b.Name;
// do something with name
}
}
Try this:
(sender as Button).Name
source
Is it possible to create an array of controls? Is there a way to get the index of a control if more than one of the controls in the array share the same event handler?
This is certainly possible to do. Sharing the event handler is fairly easy to do in this case because the Button which raised the event is sent as part of the event args. It will be the sender value and can be cast back to a Button
Here is some sample code
class Form1 : Form {
private Button[] _buttons;
public Form1(int count) {
_buttons = new Button[count];
for ( int i = 0; i < count; i++ ) {
var b = new Button();
b.Text = "Button" + i.ToString()
b.Click += new EventHandler(OnButtonClick);
_buttons[i] = b;
}
}
private void OnButtonClick(object sender, EventArgs e) {
var whichButton = (Button)sender;
...
}
}
Based on Kevins comment:
foreach(Button b in MyForm.Controls.OfType<Button>())
{
b.Click += Button_Click;
}
void Button_Click(object sender, EventArgs e)
{
Button clickedButton = sender as Button;
}