How to assign click event - c#

I have an array of button which is dynamically generated at run time. I have the function for button click in my code, but I can't find a way to set the button's click name in code. So,
what is the code equivalent for XAML:
<Button x:Name="btn1" Click="btn1_Click">
Or, what should I place for "????" in the following Code:
Button btn = new Button();
btn.Name = "btn1";
btn.???? = "btn1_Click";

Button btn = new Button();
btn.Name = "btn1";
btn.Click += btn1_Click;
private void btn1_Click(object sender, RoutedEventArgs e)
{
// do something
}

The following should do the trick:
btn.Click += btn1_Click;

// sample C#
public void populateButtons()
{
int xPos;
int yPos;
Random ranNum = new Random();
for (int i = 0; i < 50; i++)
{
Button foo = new Button();
Style buttonStyle = Window.Resources["CurvedButton"] as Style;
int sizeValue = ranNum.Next(50);
foo.Width = sizeValue;
foo.Height = sizeValue;
foo.Name = "button" + i;
xPos = ranNum.Next(300);
yPos = ranNum.Next(200);
foo.HorizontalAlignment = HorizontalAlignment.Left;
foo.VerticalAlignment = VerticalAlignment.Top;
foo.Margin = new Thickness(xPos, yPos, 0, 0);
foo.Style = buttonStyle;
foo.Click += new RoutedEventHandler(buttonClick);
LayoutRoot.Children.Add(foo);
}
}
private void buttonClick(object sender, EventArgs e)
{
//do something or...
Button clicked = (Button) sender;
MessageBox.Show("Button's name is: " + clicked.Name);
}

I don't think WPF supports what you are trying to achieve i.e. assigning method to a button using method's name or btn1.Click = "btn1_Click". You will have to use approach suggested in above answers i.e. register button click event with appropriate method
btn1.Click += btn1_Click;

You should place below line
btn.Click = btn.Click + btn1_Click;

Related

How to add buttons with independent click event

I want to add buttons and textboxes dynamically on runtime with each
button react differently.
ie newbutton1 linked with texbox1 ,newbutton2linked withtextbox2`
Right now any button just prints from the first to the last textbox
one after the other.
Also consider that I have a button1 & textbox1 already on the form for guides
Here is my code :
List<Button> buttons = new List<Button>();
List<TextBox> textboxes = new List<TextBox>();
int NumTextBox = 0;
void click(object sender, EventArgs e)
{
MessageBox.Show(textboxes[NumTextBox].Text);
NumTextBox++;
}
int x = 0;
int y = 0;
void AddClick(object sender, EventArgs e)
{
Button newButton = new Button();
buttons.Add(newButton);
newButton.Click += click;//
// newButton.Location.Y = button1.Location.Y + 20;
newButton.Location = new Point(button1.Location.X, button1.Location.Y+25+x);
x += 25;
this.Controls.Add(newButton);
TextBox newTextBox = new TextBox();
textboxes.Add(newTextBox);
// newTextBox.Click += click;
newTextBox.Location = new Point(textBox1.Location.X, textBox1.Location.Y+25+y);
y += 25;
this.Controls.Add(newTextBox);
}
you can have a class like mybutton that inherits from button class, in this new class you can have a property with textbox type . just like following code . and in your code when you want to Instantiated Button you can use list<mybutton> and set linkedTextbox property with a textbox.
public class myButton:Button
{
...
public TextBox linkedTextBox{set;get;}
}
and in your code you should write some thing like this :
list<myButton> buttons=new list<myButton>();
Textbox someTextBox=new TextBox();
buttons[0].linkedTextbox=someTextBox;
and in your event you can use:
((myButton)sender).linkedTextBox.text="Some thing";
Thank you everyone , I followed #Franck's answer .So WHAT CHANGED :
I've deleted the pre-made button1 & textbox1 and add them
programatically on the Form_load so that I can add them in the
Lists
A proof screenshot : http://prntscr.com/aprqxz
CODE:
List<Button> buttons = new List<Button>();
List<TextBox> textboxes = new List<TextBox>();
Button button1 = new Button();
TextBox textBox1 = new TextBox();
int x = 0;
int y = 0;
void click(object sender, EventArgs e)
{
var txt = textboxes[Convert.ToInt32(((Button)sender).Tag)].Text;
MessageBox.Show(txt.ToString());
}
void AddClick(object sender, EventArgs e)
{
Button newButton = new Button();
newButton.Click += click;
newButton.Location = new Point(button1.Location.X, button1.Location.Y+25+x);
x += 25;
newButton.Tag = buttons.Count;
this.Controls.Add(newButton);
buttons.Add(newButton);
//
TextBox newTextBox = new TextBox();
newTextBox.Location = new Point(textBox1.Location.X, textBox1.Location.Y+25+y);
y += 25;
this.Controls.Add(newTextBox);
textboxes.Add(newTextBox);
}
void MainFormLoad(object sender, EventArgs e)
{
button1.Click += click;
button1.Location = new Point(55, 48);
button1.Tag = buttons.Count;
this.Controls.Add(button1);
buttons.Add(button1);
//
textBox1.Location = new Point(137, 50);
this.Controls.Add(textBox1);
textboxes.Add(textBox1);
}
EDIT 1: As the counting starts from 0 I didn't added newButton.Tag = buttons.count+1; I added just newButton.Tag = buttons.count;

C# Button visible change when button cliked

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

How to add event on control created during runtime

I want to create click event on buttons, (2 Buttons are creating during runtime)
I am using this to create buttons:
private void Form1_Load(object sender, EventArgs e)
{
for (int k = 0; k < 2; k++)
{
Button Btn = new Button();
Btn.Name = "btn" + k;
Btn.Location = new System.Drawing.Point(20 + (k *110), 60 + (20 * j) * 2);
Btn.Size = new System.Drawing.Size(90, 30);
if (k == 0)
Btn.Text = "Back";
else
Btn.Text = "Calculate";
this.Controls.Add(Btn);
}
}
Thanks in Advance.
Enhance your loop like this:
for (int k = 0; k < 2; k++)
{
Button Btn = new Button();
Btn.Name = "btn" + k;
Btn.Location = new System.Drawing.Point(20 + (k *110), 60 + (20 * j) * 2);
Btn.Size = new System.Drawing.Size(90, 30);
if (k == 0)
Btn.Text = "Back";
else
Btn.Text = "Calculate";
Btn.Click += button_Click; // <-- This is where it happens!
this.Controls.Add(Btn);
}
Then add the event handler:
private void button_Click(object sender, EventArgs e)
{
Button btn = sender as Button;
if (btn.Name.Equals("..."))
{
}
else
{
}
}
Please note that within the event handler you need to decide which button has been pressed by looking at the Name property.
Simply use:
Btn.Click += button1_Click;
private void button1_Click(object sender, EventArgs e)
{
}
Like this
btn1.Click += new EventHandler(this.btn1_Click);
Btn.Click += Btn_Click;
void Btn_Click(object sender, EventArgs e)
{
throw new NotImplementedException();
}
in VS you can type Btn.Click += the press tab twice and it will generate the method for you.

WPF: how to call method by setting tag of a dynamically created buttons

3 problems in my WPF(window phone) simple project. I have spent lot of time by solving it but no specific result found..
In my cs file I have Created bunch of dynamic buttons...I crated with for loop and set tags for each dynamic button.
My cs File code is here.
private void Grid_View_Btn_1_Click(object sender, System.Windows.RoutedEventArgs e)
{
//Grid ButtonsAddition
Dispatcher.BeginInvoke(() =>
{
string[] Trade = new string[] { "Portfolio Display", "Trade Idea Entry", "Trade Idea Monitor", "Historical Performance", "Intraday Performance", "Stock Performance" };
StackPanel panel = new StackPanel();
panel.Orientation = System.Windows.Controls.Orientation.Vertical;
//panel.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;
//panel.VerticalAlignment = System.Windows.VerticalAlignment.Top;
int i;
for (i = 0; i < Trade.Length; i++)
{
Button btn = new Button() { Content = Trade[i] };
btn.Margin = new Thickness(0, -10, 0, -10);
var brush = new ImageBrush();
brush.ImageSource = new BitmapImage(new Uri("C:/Users/HafizArslan/Documents/Visual Studio 2012/Projects/AimPass/AimPass/Images/tabbar_btn_blue.png", UriKind.Relative));
btn.Background = brush;
btn.Width = 190;
btn.Height = 75;
btn.FontSize = 14;
btn.FontWeight = light;
btn.FontStretch = Fill;
btn.HorizontalAlignment = HorizontalAlignment.Center;
btn.VerticalAlignment = System.Windows.VerticalAlignment.Stretch;
// btn.CornerRadius = new CornerRadius(15);
btn.BorderThickness = new Thickness(1, 1, 1, 1);
btn.Tag = i.ToString();
btn.Click += new RoutedEventHandler(abc_click);
panel.Children.Add(btn);
}
grid.Children.Add(panel);
});
}
private void abc_click(object sender, EventArgs e)
{
}
There are 6 buttons creted.
the problem is I want to perform different actions with button...I have set Tags but I dont know how can I access an actions with buttons Tag..?
I mean I want something like this...!!
private void abc_click(object sender, EventArgs e)
{
// If(btn.Tag==1)
{
//Some Code Here
}
else
if(btn.Tag==2) {
//Perform other Function
}
} Etc.....?
and other problem is I have made a image brush..Assign exact path of image...for every created button background....But Image is not attached...
Kindly tell me about these 2 problems...
You have sender in handler, you can type cast sender to button and access Tag property from it:
private void abc_click(object sender, EventArgs e)
{
Button button = (Button)sender;
if(Convert.ToInt32(button.Tag) == 1)
{
.....
}
}
In your for loop, you can associate handler to the button.
Such as:
Button btn = new Button() { Content = Trade[i] };
btn.Margin = new Thickness(0, -10, 0, -10);
if(<something>)
btn.Click += YourEventHandler1;
if(<something2>)
btn.Click += YourEventHandler2;
If you want to access tag property, you need to cast the sender to Button, as so:
private void abc_click(object sender, EventArgs e)
{
var btn = (Button)sender;
}
you should go with this
var tag=((sender as Button).Tag).ToString();
////now use a switch
Switch(tag)
{
case "1":
//Action
break;
case "2":
//Acrion
break;
//more cases
}
hope this helps.
if for all created buttons the event is same then One approach could be to get the tag in the event like this
int tag=Convert.ToInt32((sender as Button).Tag);
now use a switch
switch(tag)
{
case 1:
//Action
break;
case 2:
//Acrion
break;
//more cases
}
hope this helps.

Assign MouseHover event to newly created Control

This is the new control add code part:
for (int i = 0; i < 1; i++)
{
var newLabel = new Label();
newLabel.Location = new Point(x, y);
newLabel.Size = new System.Drawing.Size(25, 25);
newLabel.Name = "lbl" + realpocsed.ToString();
if (value2== "Value2")
{
newLabel.MouseMove += new MouseEventHandler(this.MyControl_MouseMove);
newLabel.MouseDown += new MouseEventHandler(this.MyControl_MouseDown);
}
if (value== "Value1")
{
newLabel.MouseDown += new MouseEventHandler(this.MyControl_MouseHover);
}
panel1.Controls.Add(newLabel);
The MouseHover event look like this:
private void MyControl_MouseHover(object sender, MouseEventArgs e)
{
ToolTip ToolTip1 = new ToolTip();
ToolTip1.ShowAlways = true;
ToolTip1.Show("t", X); // X should be name of the newly created label
}
May I ask if is there any way to assign the newly created with name "lbl" + realpocsed.ToString() instead of X?
Thank you for your time.
You're assigning a MouseDown event to your MouseHover code, not sure you want that.
It should look like this:
newLabel.MouseHover += MyControl_MouseHover;
For your X, you would have to cast the sender:
ToolTip1.Show("Hover Message Here", (Label)sender);
You can't access any object by creating its name in string. The simple way to do that is to pass the object reference:
ToolTip1.Show("t", (sender as Label));
Inside for:
newLabel.MouseHover += delegate (object sender, EventArgs e)
{
ToolTip ToolTip1 = new ToolTip();
ToolTip1.ShowAlways = true;
ToolTip1.Show("t", newLabel);
};
Update:
if (value == "Value1")
{
newLabel.MouseHover += delegate (object sender, EventArgs e)
{
ToolTip ToolTip1 = new ToolTip();
ToolTip1.ShowAlways = true;
ToolTip1.Show("t", newLabel);
};
}

Categories

Resources