I am creating a 2d array of buttons using code and I want to add a button_click() method.
Besides the 2 usual arguments (object sender, EventArgs e) I want to get as an input 2 more variables, To identify which button was clicked, and do something else as a result.
I am currently doing this
arr[i,j].Click+= new EventHandler(button_click);
public void button_click(object sender, EventArgs e)
Is there another way of adding events that will allow me to do what I want?
And on a seperate note. Is there an easy way of creating cubes with a certain color without using buttons?
To identify which button was clicked, and do something else as a result.
You could use sender parameter to identify the button which was clicked.
If you do not want to introduce a custom button type which would have properties for i and j, you could use Tag property to store the indices.
Create a class which inherits from button class. And add 2 properties to it. Then access those properties in your form . Following example is one way to solve your problem.
public class ButtonCtrl : Button
{
public ButtonCtrl(int _arg1, int _arg2)
{
Arg1 = _arg1;
Arg2 = _arg2;
}
public int Arg1 { get; set; }
public int Arg2 { get; set; }
}
//create buttons in form c'tor
public Form1()
{
InitializeComponent();
ButtonCtrl button1 = new ButtonCtrl(1,2);
button1.Text = "dynamic 1";
button1.Click += new EventHandler(button_click);
button1.Top = 10;
this.Controls.Add(button1);
ButtonCtrl button2 = new ButtonCtrl(3, 4);
button2.Text = "dynamic 2";
button2.Click += new EventHandler(button_click);
button2.Top = 30;
this.Controls.Add(button2);
}
And the event handler
public void button_click(object sender,EventArgs e)
{
if(sender is ButtonCtrl)
{
ButtonCtrl btnCtrl= sender as ButtonCtrl;
label1.Text = btnCtrl.Arg1.ToString() + " " + btnCtrl.Arg2.ToString();
}
}
Related
I am working on a WinForms application where I want the user to click a button and then change the button's text (add +1 to the counter). I have multiple buttons and having three methods Click MouseDown and MouseUp for each of those would be pretty inefficient.
So I've set up a class, but don't know how to assign it to all the buttons.
public class AddButton : Button
{
public int Count { get; set; }
private void Button_Click(object sender, EventArgs e)
{
AddButton ab = (AddButton)sender;
Count++;
ab.Text = Count + " Added";
}
}
Maybe I could also just link all the button's EventHandlers to one, but I don't know how to start there and where to put the code. Here is the Visual Studio project download link if you need it.
You could try this code:
public class AddButton:Button
{
public int Count { get; set; } = 0;
public AddButton()
{
// After it's painted, set its text to current Counter
this.Paint += (s, e) => this.Text = Count.ToString();
this.Click += (s, e) => this.Text = (++Count).ToString();
}
}
In your project it's enough to change buttons initialization from:
Button button1 = new Button();
to
Button button1 = new AddButton();
// or
AddButton button1 = new AddButton();
I have written a function AddItem that adds an item to a listview. I also have created a function to create dynamic buttons. But once i create a dynamic button i would like it to have the AddItem function work when the button is pressed.
I have no clue how i would solve this because im relatively new to C# and windows forms.
private void AddButton(string Name, string Text, int Posx, int Posy, double Price, string ItemName)
{
// Create a Button object
Button NewButton = new Button();
// Set Button properties
NewButton.Height = 50;
NewButton.Width = 120;
NewButton.BackColor = Color.Gainsboro;
NewButton.ForeColor = Color.Black;
NewButton.Location = new Point(Posx, Posy);
NewButton.Text = Text;
NewButton.Name = Name;
NewButton.Font = new Font("Microsoft Sans Serif", 12);
// Add a Button Click Event handler
NewButton.Click += new EventHandler(NewButton_Click);
//Add to form ontop of panelButtonHamburgers
panelButtonsHamburgers.Controls.Add(NewButton);
}
private void NewButton_Click(object sender, EventArgs e)
{
AddItem(Price, ItemName);
}
As you can see the AddButton function takes a price and itemname, once the button is clicked i would like the additem function to run with this same price and itemname.
Thanks!
As far as I understood, you need a hanlder that uses some specific values for each dynamic button. There are few approaches you can use.
Use Tag property and save values in some format
newBut.Tag = $"{Price},{ItemName}";
and than, in handler
//always check for null
Button button = sender as Button;
string data = button.Tag as string;
//do staff with your data
Create Dictionary and every time you add new button add it as a key to Dictionary and that, in handler get your data (but this is one of the worst way to do it, so try to avoid it);
Use "Command" pattern. Make a special class for executing your operation. It should look like this
class MyCommand
{
public double Price { get; set; }
public string Name { get; set; }
public ListView List { get; set; } //here is the list you want to add item to.
public void Handle (object sender, EventArgs e)
{
//Do your staff here
}
}
It is a little bit tricky but introduces good pattern you can use in future.
You could assign a tuple to the button's Tag.
private void AddButton(string Name, string Text, int Posx, int Posy, double Price, string ItemName)
{
...
NewButton.Tag = (Price, ItemName);
}
Then you can the get that tuple's values from the sender in the event, which actually is the button.
private void NewButton_Click(object sender, EventArgs e)
{
double price = (((double Price, string ItemName))((Button)sender).Tag).Price;
string itemName = (((double Price, string ItemName))((Button)sender).Tag).ItemName;
...
}
So I was trying to send custom arguments to an event, but it never worked, I tried so many different methods, but I never got it to work,
So basically!
public void CreateEmojiList()
{
CreateAllEmojis();
int btnCount = 0;
foreach(Emoji emoji in emojiList)
{
Button btnEmoji = new Button();
btnEmoji.Size = new Size(40, 36);
btnEmoji.FlatStyle = FlatStyle.Flat;
btnEmoji.FlatAppearance.MouseDownBackColor = Color.Cyan;
btnEmoji.Cursor = Cursors.Hand;
btnEmoji.Font = new Font("Bahnschrift", 6.75f);
btnEmoji.Text = emoji.EmojiText;
btnEmoji.Top = (panel_main.Controls.OfType<Button>().Count<Button>() / 4) * (1 + btnEmoji.Height) + 6;
btnEmoji.Left = (btnEmoji.Width + 1) * btnCount + 6;
panel_main.Controls.Add(btnEmoji);
btnEmoji.Click += //What do I do here?
; btnCount++;
if (btnCount == 4)
btnCount = 0;
}
}
protected virtual void OnEmojiClick(EmojiClickEventArgs e)
{
if (this.EmojiClick != null)
EmojiClick(e);
}
this is the class I want to use to pass my arguments:
public class EmojiClickEventArgs : EventArgs
{
private string emojiText;
private string emojiName;
public EmojiClickEventArgs(string EmojiText, string EmojiName)
{
this.EmojiText = EmojiText;
this.EmojiName = EmojiName;
}
public string EmojiText { get { return emojiText; } set { emojiText = value; } }
public string EmojiName { get { return emojiName; } set { emojiName = value; } }
}
I want to get those two values from
emoji.EmojiText and emoji.EmojiName
You can take advantage of closures to "package up" the additional event data for each button's event handler. Just make sure not to close over the loop variable.
public void CreateEmojiList()
{
CreateAllEmojis();
int btnCount = 0;
foreach(Emoji emoji in emojiList)
{
Button btnEmoji = new Button();
btnEmoji.Size = new Size(40, 36);
btnEmoji.FlatStyle = FlatStyle.Flat;
btnEmoji.FlatAppearance.MouseDownBackColor = Color.Cyan;
btnEmoji.Cursor = Cursors.Hand;
btnEmoji.Font = new Font("Bahnschrift", 6.75f);
btnEmoji.Text = emoji.EmojiText;
btnEmoji.Top = (panel_main.Controls.OfType<Button>().Count<Button>() / 4) * (1 + btnEmoji.Height) + 6;
btnEmoji.Left = (btnEmoji.Width + 1) * btnCount + 6;
panel_main.Controls.Add(btnEmoji);
var emojiCopy = emoji; //don't close on the loop variable!
btnEmoji.Click += (sender,args) => OnEmojiClick(emojiCopy);
btnCount++;
if (btnCount == 4)
btnCount = 0;
}
}
protected virtual void OnEmojiClick(Emoji emoji)
{
//do something
}
One way is to inherit from Button and create a class called EmojiButton. You then declare a delegate that matches the signature of the your event handler. After that, declare an event using the delegate in the EmojiButton class, add property like EmojiText and EmojiName to the button subclass as well. Finally you need to link the button click event with your custom event. Whenever the button is clicked, raise your event and pass your arguments i.e. this.EmojiText, this.EmojiName.
Another way is to assign your Emoji objects to the Tag property. You can then write the event handler with the normal EventHandler signature (object sender, EventArgs e), and look at what the sender's Tag is. You then cast the Tag to an Emoji and access its properties.
The fastest solution that comes to my mind and that doesn't imply the definition of custom UserControl classes, the subclassing of Button and other similar practices is:
btnEmoji.Click += (sender, e) =>
{
Button b = (Button)sender;
// let's suppose that the button name corresponds to the emoji name
String emojiName = b.Name;
// let's suppose that the button tag contains the emoji text
String emojiText = (String)b.Tag;
Emoji_Clicked(sender, e, (new EmojiClickEventArgs(emojiText, emojiName)));
};
private void Emoji_Clicked(Object sender, EventArgs e, EmojiClickEventArgs ee)
{
// Your code...
}
First and foremost thing you need to define delegate ,then create an instance.
class Emojis
{
// public delegate void EmojiClickEventHandler(object sender,EventArgs args);
//public event EmojiEventHandler EmojiClicked;
//you can use above two lines or replace them instead below code.
public event EventHandler<EmojiClickEventArgs> EmojiClicked;
public void CreateEmojiList()
{
CreateAllEmojis();
int btnCount = 0;
//rest of the code
panel_main.Controls.Add(btnEmoji);
btnEmoji.Click += OnEmojiClick(btnEmoji);
btnCount++;
}
protected virtual void OnEmojiClick(Button emoji)
{
//Here null check to handle if no subscribers for the event
if(EmojiClicked!=null)
{
//there is no name property define for emoji but only text hence passing only text.
EmojiClicked(this ,new EmojiClickEventArgs(emoji.Text,emoji.Text){ });
}
}
private void Emoji_Clicked(Object sender, EmojiClickEventArgs args)
{
Button mybutton = sender as Button;
Console.WriteLine("emoji text "+ args.Text);
}
}
I am writing a simple calculator script for my C# programming class. It will of course have buttons 0-9 that will update the output textbox to add the number of whatever button is clicked. My problem right now that is I would rather not have to have 10 different click events in my script. I would rather have a loop that cycles through the buttons that will add the same click event to each one and then decide what number to add to the output based on the button.
So right now, I have a click event for the "1" button which is this...
private void btnNum1_Click(object sender, EventArgs e)
{
txtOutput.Text = Convert.ToString(txtOutput.Text + "1");
}
This works fine, but, again, I would rather not have to do this 10 times. How can I create a loop that prevents this?
The button names are btnNum1, btnNum2, btnNum3, etc.
Assuming the button text is just "1", "2" etc you could do this:
private void btnNum_Click(object sender, EventArgs e)
{
var button = sender as Button
txtOutput.Text += button.Content.ToString();
}
Then just apply this event to all the buttons.
Also note you don't need Convert.ToString() as what you are trying to convert is already a string. Using += also cleans up your code a bit.
You could do this to wire-up all of the events in one go:
for (var n = 0; n <= 9; n++)
{
var btn =
this
.Controls
.Find("btnNum" + n.ToString(), false)
.Cast<Button>()
.First();
var digit = n;
btn.Click += (s, e) =>
{
txtOutput.Text = digit.ToString();
};
}
You could enumerate the children controls of your Form/Control, look the type of controls which are type of Button and the name StartWith 'btnNum', with each of these buttons, add a Click event address to btnNum_Click().
Say if all your buttons are contained in a Panel named 'pnlButtons', you could loop all the children like this.
foreach (var control in pnlButtons.Controls)
{
if(control.GetType() == typeof(Button))
{
var button = control as Button;
if (button .Name.StartWith('btnNum'))
{
button.Click += btnNum_Click;
}
}
}
You can use the "Tag" property of the Button control and make an array of Buttons to subscribe to the same event. See sample below:
void InitializeButtons()
{
Button btnNum1 = new Button();
btnNum1.Text = "1";
btnNum1.Tag = 1;
//Button 2..8 goes here
Button btnNum9 = new Button();
btnNum9.Text = "9";
btnNum9.Tag = 9;
Button[] buttons = new Button[]{
btnNum1, btnNum2, btnNum3, btnNum4, btnNum5, btnNum6, btnNum7, btnNum8, btnNum9
};
for (int i = 0; i < buttons.Length; i++)
{
buttons[i].Click += Button_Click;
}
}
void Button_Click(object sender, EventArgs e)
{
Button button = (Button)sender;
int value = (int)button.Tag;
//Do something with value
}
Assuming WinForms, you can recursively search for buttons that start with "btnNum" and wire them up to a common handler like this:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.Load += Form1_Load;
}
void Form1_Load(object sender, EventArgs e)
{
FindButtons(this);
}
private void FindButtons(Control ctl)
{
foreach(Control ctrl in ctl.Controls)
{
if (ctrl.Name.StartsWith("btnNum") && (ctrl is Button))
{
Button btn = (Button)ctrl;
btn.Click += btn_Click;
}
else if(ctrl.HasChildren)
{
FindButtons(ctrl);
}
}
}
private void btn_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
txtOutput.Text = Convert.ToString(txtOutput.Text + btn.Text);
}
}
I'm trying to create a matching game that consists of 12 buttons. The program assigns a random string from an array that has 12 strings in it. When the button is pressed, the tag is passed to the button.text.
What I'm trying to accomplish now is, for example. If I press "button 1", the text of it changes to "Chevy Camaro". If I press "button 4" next, I want the button1.text to revert back to saying "button 1", rather than it's tag value of "Chevy Camaro". And in like fashion, since "button 4" was pressed, I would like it to show the tag.....
Each button has similar code to it, besides the button #, which of course changes based on the button that's being used.
I'm unsure how to state that, if button is the current active item, then show it's tag property, otherwise, revert back.
private void button4_Click(object sender, EventArgs e)
{
button4.Text = button4.Tag.ToString();
buttoncount++;
label2.Text = buttoncount.ToString();
}
Thanks in advance for all of your help. Slowly learning this stuff.... =p
You could keep track of the last button that was clicked:
public partial class Form1 : Form
{
Button lastButton = null;
int buttoncount;
public Form1()
{
InitializeComponent();
button1.Tag = "Ford Mustang";
button2.Tag = "Ford Focus";
button3.Tag = "Chevy Malibu";
button4.Tag = "Chevy Camaro";
button1.Click += button_Click;
button2.Click += button_Click;
button3.Click += button_Click;
button4.Click += button_Click;
//etc...
}
void button_Click(object sender, EventArgs e)
{
if (lastButton != null)
{
SwitchTagWithText();
}
lastButton = sender as Button;
SwitchTagWithText();
buttoncount++;
label2.Text = buttoncount.ToString();
}
void SwitchTagWithText()
{
string text = lastButton.Text;
lastButton.Text = lastButton.Tag.ToString();
lastButton.Tag = text;
}
}
Could you use a RadioButton control with its appearance set to button? Replace all buttons with these, put them in a GroupBox and the 'reverting' of appearance when clicked off can be automatically handled. To update the text, a simple event handler like below will do;
private void MakeButton()
{
RadioButton rb = new RadioButton
{
Appearance = Appearance.Button,
Tag = "Chevy Camero"
};
rb.CheckedChanged += rb_CheckedChanged;
}
private void rb_CheckedChanged(object sender, EventArgs e)
{
RadioButton clickedButton = sender as RadioButton;
string currentText = clickedButton.Text;
clickedButton.Text = clickedButton.Tag.ToString();
clickedButton.Tag = currentText;
}