I've seen many examples of how to add a click event to a dynamically created button, but none of the examples show how to pass arguments with the event.
I am new to C# and just looking for a simple solution. See the code below:
public partial class Main : Form {
public Main() {
InitializeComponent();
// Add a button dynamically
Button Test = new Button();
this.Controls.Add(Test);
Test.Left = 0;
Test.Top = 0;
Test.Width = 100;
Test.Height = 20;
Test.Text = "Hello";
int param1 = 1;
string param2 = "Test";
// Add click event handler with parameters ????
// I know this syntax is wrong, but how do I get param1 & 2
// into the Test_Click ????
Test.Click += Test_Click(param1,param2);
}
private void Test_Click(int param1, string param2) {
MessageBox.Show(param1.ToString() + ": " + param2);
}
You do not provide arguments when adding the event but you provide it in the event it self, in this case the click event arguments are:
private void Test_Click(object sender, EventArgs e)
{
}
the first argument is usually object sender while the second changes depending on the event type, in case of click event it's "EventArgs e"
and for the adding event :
Test.Click += Test_Click;
Hope i helped you.
Ok. I know this is a little ugly, but this is what I came up with from the comments above. If there is a better way to do this, please let me know:
public partial class Main : Form {
public Dictionary<object, Tuple<int, string>> Params = new Dictionary<object, Tuple<int,string>>();
public Main() {
InitializeComponent();
// Add a button dynamically
Button Test = new Button();
this.Controls.Add(Test);
Test.Left = 0;
Test.Top = 0;
Test.Width = 100;
Test.Height = 20;
Test.Text = "Hello";
Test.Name = "Test";
// Add click event handler with parameters
Params.Add(Test, new Tuple<int, string>(1, "Test"));
Test.Click += Test_Click;
}
private void Test_Click(object sender, EventArgs e) {
Tuple<int,string> value;
if (Params.TryGetValue(sender, out value)) {
MessageBox.Show(value.Item1.ToString() + ": " + value.Item2);
}
else {
MessageBox.Show(sender.ToString() + " not found.");
}
}
Here is another solution I came up with without using Dictionary or Tuple by adding the button and the parameters together into a class structure. I like this one better:
class MyButton {
private Button oButton;
private int iParam1;
private string sParam2;
public MyButton(Form Me, int Left, int Top, int Width, int Height, string Text, int Param1, string Param2) {
oButton = new Button();
Me.Controls.Add(oButton);
oButton.Left = Left;
oButton.Top = Top;
oButton.Width = Width;
oButton.Height = Height;
oButton.Text = Text;
iParam1 = Param1;
sParam2 = Param2;
oButton.Click += Click;
}
private void Click(object sender, EventArgs e) {
MessageBox.Show(iParam1.ToString() + ": " + sParam2);
}
}
public partial class Main : Form {
public Main() {
InitializeComponent();
MyButton Test = new MyButton(this, 0, 0, 100, 20, "Hello", 1, "Test");
}
}
Here's a bit cleaner version of what I was talking about (sorry, I wasn't near a computer earlier). The initial implementation of Tuple was truly clunky; it's since become part of the language.
I started with the auto-generated:
public partial class MyForm : Form
{
public MyForm()
{
InitializeComponent();
}
}
And then added this to the form class:
private Dictionary<string, (int param1, string param2)> _parametersMap = new Dictionary<string, (int param1, string param2)>();
If you are using the latest compiler, you can simplify this to:
private Dictionary<string, (int param1, string param2)> _parametersMap = new();
Then I added a method to the form class that the click handler will call:
public void ShowSomething (string buttonName, int i, string s)
{
MessageBox.Show(this, $"Button: {buttonName} cliked: i={i}, s = {s}");
}
All button click handlers have the same method signature. It's determined by the code that raises the click event. So...
public void OnDynamicButtonClick (object sender, EventArgs e)
{
if (sender is Button button)
{
var (param1, param2) = _parametersMap[button.Name];
ShowSomething(button.Name, param1, param2);
}
}
Notice that the if statement uses a pattern matching if mechanism. The code within the if sees button as the sender cast to a Button.
Then, to match your initial code, I put this in the form constructor (after InitializeComponent. It really doesn't belong there. It should be in some event handler, at the very least the Form Load handler, more likely wherever it is that you want to create the buttons (creating them in the constructor kind of defeats the idea of dynamically constructing them):
var firstButton = new Button
{
Name = "FirstButton",
Text = "First",
Location = new Point(100, 100),
Size = new Size(200, 50),
Parent = this,
};
firstButton.Click += OnDynamicButtonClick;
_parametersMap.Add(firstButton.Name, (42, "Test1"));
Controls.Add(firstButton);
var secondButton = new Button
{
Name = "SecondButton",
Text = "Second",
Location = new Point(100, 300),
Size = new Size(200, 50),
Parent = this,
};
secondButton.Click += OnDynamicButtonClick;
_parametersMap.Add(secondButton.Name, (111, "Test2"));
Controls.Add(firstButton);
Note that I created two buttons, both pointing to the same button click handler (that's the point of the sender argument.
If you are going to be doing this a lot, an alternative approach would be to sub-class the Button class, adding your Param1 and Param2 as properties:
public class MyButtonSubClass : Button
{
public int Param1 { get; set; }
public string Param2 { get; set; }
}
(hopefully giving them more meaningful names)
Instances of your subclass are Buttons, just with two extra properties, so you can do this:
var firstButton = new MyButtonSubclass
{
Name = "FirstButton",
Text = "First",
Location = new Point(100, 100),
Size = new Size(200, 50),
Parent = this,
Param1 = 42,
Param2 = "Some Test",
};
firstButton.Click += OnDynamicButtonClick;
Controls.Add(firstButton);
//same for the second button
And then change the click event handler to:
public void OnDynamicButtonClick (object sender, EventArgs e)
{
if (sender is MyButtonSubclass button)
{
ShowSomething(button.Name, button.Param1, button.Param2);
}
}
And the program will appear to work in the same way.
Or, at this point, you could change the event handler to look like:
public void OnDynamicButtonClick(object sender, EventArgs e)
{
if (sender is MyButtonSubclass button)
{
MessageBox.Show(this, $"Button: {button.Name} cliked: i={button.Param1}, s = {button.Param1}");
}
}
so what i would like to is setting back some attributes after an Custom Event is finished.
Scenario i have a save BackupDrives Class that does collection of data and then offers a Event to be called after its done.
Changing object properties can be done by button click, what i would like is to set them back to the same value after the event is finished.
Button click does the thing :
private void bbdrives_Click(object sender, RoutedEventArgs e)
{
backup.SaveDrives += OnSavingDrives;
backup.DrivesSave();
Drive_text.Visibility = Visibility.Visible;
drives_progres.Visibility = Visibility.Visible;
drives_progres.IsIndeterminate = true;
}
Now the triggered event method is not able to change the properties back.
private void OnSavingDrives(object sender, DrivesEventArgs e)
{
Directory.CreateDirectory(....);
File.WriteAllLines(e.Something, e.List2ToSave);
File.WriteAllLines(e.Something_lse, e.List1ToSave);
Drive_text.Visibility = Visibility.Collapsed;
drives_progres.Visibility = Visibility.Collapsed;
drives_progres.IsIndeterminate = false;
}
How do i do this. Since this does not work.
And on other thig here to - when i run the GUI i need to click 2 times one the same button to start it all. Done Code Clean + Rebuild. Still the same.
---EDIT---
As for code here you go.
This is a Class for collecting method and event.
public class DrivesEventArgs : EventArgs
{
string MYDOC = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
const string backup_Drives = "....";
const string backup_Letters = "...";
public List<string> List1ToSave = new List<string>();
public List<string> List2ToSave = new List<string>();
public string SAVE_DRIVE_Letter
{
get
{
string name = Path.Combine(MYDOC, backup_Letters);
return name;
}
}
public string SAVE_DRIVE_Path
{
get
{
string name = Path.Combine(MYDOC, backup_Drives);
return name;
}
}
}
public class DrivesBackup
{
private const string path = "Network";
private List<string> drives_to_save = new List<string>();
private List<string> letters_for_drives = new List<string>();
private RegistryKey reg1, reg2;
public event EventHandler<DrivesEventArgs> SaveDrives;
public void DrivesSave()
{
var data = new DrivesEventArgs();
try
{
if (drives_to_save.Count == 0)
{
reg1 = Registry.CurrentUser.OpenSubKey(path);
string[] mounted_drives = reg1.GetSubKeyNames();
foreach (var drive in mounted_drives)
{ //get all UNC Paths from mounted_drives
string[] getUNC = { path, drive };
string fullUNC = Path.Combine(getUNC);
reg2 = Registry.CurrentUser.OpenSubKey(fullUNC);
string UNCPath = reg2.GetValue("RemotePath").ToString(); //getting UNC PATH
Console.WriteLine(UNCPath);
data.List1ToSave.Add(drive.ToString());
data.List2ToSave.Add(UNCPath);
OnSaveDrives(data);
}
}
}
catch (Exception er)
{
throw er;
}
}
protected virtual void OnSaveDrives(DrivesEventArgs eD)
{
SaveDrives?.Invoke(this, eD);
}
Now here is the MAINWINDOW WPF
public partial class MainWindow : Window
{
DrivesBackup backup = new DrivesBackup();
public MainWindow()
{
InitializeComponent();
}
private void bbdrives_Click(object sender, RoutedEventArgs e)
{
backup.DrivesSave();
backup.SaveDrives += OnSavingDrives;
Drive_text.Visibility = Visibility.Visible;
drives_progres.Visibility = Visibility.Visible;
drives_progres.IsIndeterminate = true;
}
private void OnSavingDrives(object sender, DrivesEventArgs e)
{
Directory.CreateDirectory(System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), #"SEG-Backup"));
File.WriteAllLines(e.SAVE_DRIVE_Path, e.List2ToSave);
File.WriteAllLines(e.SAVE_DRIVE_Letter, e.List1ToSave);
Drive_text.Visibility = Visibility.Collapsed;
drives_progres.Visibility = Visibility.Collapsed;
drives_progres.IsIndeterminate = false;
}
}
Now i do hope this would make some things more clear.
I have a dynamical create button object where I want it to send an event to the mainform when I click on a button inside this object.
I have the code like this :
class Class1
{
internal class FObj_BtnRow
{
private Button[] _Btnmembers;
internal event EventHandler<SelValue_EArgs>[] e_BtnMember; //subscribe to a change
internal class SelValue_EArgs : EventArgs//events args (selected value)
{//return arguments in events
internal SelValue_EArgs(Boolean ivalue) { refreshed = ivalue; }//ctor
internal Boolean refreshed { get; set; }//accessors
}
private Boolean[] _ActONOFFValue; //Pump=0, valveInput = 1, Shower = 3, Washtool = 4 , WashWPcs = 5
private Boolean ActONOFFValue(int number)
{
_ActONOFFValue[number] = !_ActONOFFValue[number];
{
if (e_BtnMember[number] != null && number == 0) e_BtnMember[number](this, new SelValue_EArgs(_ActONOFFValue[number]));
}
return _ActONOFFValue[number];
}
public FObj_BtnRow(String[] TxtBtn, String UnitName)//ctor
{
_Btnmembers = new Button[TxtBtn.Length];
e_BtnMember = new EventHandler<SelValue_EArgs>[TxtBtn.Length];
for (int i = 0; i < TxtBtn.Length / 2; i++)
{
_Btnmembers[i].Click += new EventHandler(_Btnmembers_Click);
}
}
protected virtual void _Btnmembers_Click(object sender, EventArgs e)
{
int index = Array.IndexOf(_Btnmembers, (Button)sender);
ActONOFFValue(index);
}
}
}
But in the line : internal event EventHandler[] e_BtnMember;
the compiler told me that I should use a delegate. I don't understand good this remark, could you help me?
At the end the mainform should only subscribe to the event button click it wants.
And then in main we could use it to now when a button in the object multibutton row is clicked... like this:
public void main()
{
String[] txtbtn = new String[] { "btn1", "btn2", "btn3" };
FObj_BtnRow thisbtnrow = new FObj_BtnRow(txtbtn);
thisbtnrow.e_BtnMember[0] += new EventHandler<FObj_BtnRow.SelValue_EArgs> (btnmember0haschanged);
}
public void btnmember0haschanged(object sender, FObj_BtnRow.SelValue_EArgs newvalue)
{
bool thisnewvalue = newvalue.refreshed;
}
Can you help me?
Thanks in advance!!
I solved the problem by myself, thanks for your advices.
Code
class Class1
{
internal class FObj_BtnRowtest
{
private Button[] _Btnmembers;
public delegate void del_Btnmember(Boolean value);
public del_Btnmember[] btnvaluechanged;
internal class SelValue_EArgs : EventArgs//events args (selected value)
{//return boolean arguments in events
internal SelValue_EArgs(Boolean ivalue) { refreshed = ivalue; }//ctor
internal Boolean refreshed { get; set; }//accessors
}
private Boolean[] _ActONOFFValue;
private Boolean ActONOFFValue(int number)
{
_ActONOFFValue[number] = !_ActONOFFValue[number];
return _ActONOFFValue[number];
}
public FObj_BtnRowtest(int numofbtn, String UnitName)//ctor
{
_Btnmembers = new Button[numofbtn];
btnvaluechanged = new del_Btnmember[numofbtn];
_ActONOFFValue = new bool[numofbtn];
for (int i = 0; i < numofbtn / 2; i++)
{
_Btnmembers[i].Click += new EventHandler(_Btnmembers_Click);
}
}
protected virtual void _Btnmembers_Click(object sender, EventArgs e)
{
int index = Array.IndexOf(_Btnmembers, (Button)sender);
if (btnvaluechanged[index] != null) btnvaluechanged[index](ActONOFFValue(index));
}
}
}
And then in main
thisrow = new Class1.FObj_BtnRowtest(4,"thisunittest");//4 buttons
thisrow.btnvaluechanged[0] += new Class1.FObj_BtnRowtest.del_Btnmember(valuetesthaschanged);//to subscribe to btn0 change
using delegates make it easier. and yes we do need those kinds of stuffs to make code clearer and faster to developp.
Thanks all!!
I'm trying to add a button to the form using code and iv'e looked it up on the internet but nothing works.
public void addSnake()
{
Button btn = new Button();
btn.Location = new Point(360, 390);
btn.Size = new Size(10, 10);
btn.Text = "";
btn.Name = num + "";
btn.Tag = this.oneD;
btn.IsAccessible = false;
Controls.Add(btn);
}
public Point getPoint()
{
Button btn = (Button)Controls.Find(num + "");
return this.pos; //temporary
}
it says "The name 'Controls' does not exist in the current context". (for both functions)
Note: the functions addSnake and getPoint are inside a Class I made
Full code here: deleted
Your class is not inheriting from System.Windows.Forms.Form. So there is no such property called Controls.
What you can do is pass a reference of the form to the constructor of SnakeB:
public class SnakeB
{
private System.Windows.Forms.Form parentForm;
public SnakeB(System.Windows.Forms.Form parent)
{
parentForm = parent;
}
}
and use it in your methods like this:
public Point getPoint()
{
Button b = parentForm.Controls.Find(num + "") as Button;
return b.Location;
}
public void addSnake(bool isFirst)
{
Button b = new Button();
// ...
parentForm.Controls.Add(b);
}
Usage:
public Form1()
{
InitializeComponent();
SnakeB snake = new SnakeB(this);
}
You need to have instance of the form in your class and add the control to that instance like
public class SnakeB
{
int num;
int oneD;
Point pos = new Point();
Form1 frm1 = new Form1();
frm1.Controls.Add(btn);
How will you have the instance of the form? Like below
public Form1()
{
InitializeComponent();
SnakeB snake = new SnakeB(this);
}
In your class have a similar consructor
public class SnakeB
{
int num;
int oneD;
Point pos = new Point();
Form1 frm1;
public SnakeB()
{
this.num = 0;
this.oneD = 2;
//here construct the maain head button and 2 reguler ones
addSnake(true);
addSnake(false);
addSnake(false);
}
public SnakeB(Form1 frm) : this()
{
this.frm1 = frm;
}
Increasing my score label 137 points per item I pickup
fMain
//HUD Score
public int Score()
{
labScore.Text = Convert.ToString(score);
labScore.Text = "00000" + score;
if (score >= 10)
labScore.Text = "0000" + score;
if (score >= 100)
labScore.Text = "000" + score;
if (score >= 1000)
labScore.Text = "00" + score;
return score;
}
And I want my labScore2.Text to be the same as labScore.text. But they are in different forms.
fMain2
public void btnIntroducir_Click(object sender, EventArgs e)
{
fMain f = new fMain();
f.Score();
try
{
string n = txtNombre.Text;
int s = int32.Parse(labScore2.Text);
lista[indice] = new Koby(n, s);
indice++;
muestraLista(ref lstJugadores);
txtNombre.Clear();
txtNombre.Enabled = false;
}
what you are doing is putting the value in a string that is not public. Either make the string public and access it from the other form or you can create a class and put all such variables in that class then access them from there when you need.
You could probably create a Custom Event for in FMain2 that would reflect back to your FMain LabScore.Text.
In your FMain2, create the Custom Event. Let's say we create a Custom Event with score as parameter. We will have the following:
public partial class FMain2 : Form
{
public delegate void ScoreChangedEvent(String score); // Event Handler Delegate
public event ScoreChangedEvent ScoreChanged; // Event Handler to subscribe to the Delegate
public FMain2()
{
InitializeComponent();
}
}
In your FMain you could initialize the event and make the necessary changes when event is triggered, like:
private void btnChangeScore_Click(object sender, EventArgs e)
{
FormMain2 FMain2 = new FormMain2();
FMain2.ScoreChanged += new FMain2.ScoreChangedEvent(FMain2_ScoreChanged);
FMain2.Show();
}
void FMain2_ScoreChanged(string score)
{
labScore.Text = score; // This will receive the changes from FMain2 LabScore2.Text
}
Then back in your FMain2 you add the following:
public void btnIntroducir_Click(object sender, EventArgs e)
{
try
{
string n = txtNombre.Text;
int s = int32.Parse(labScore2.Text);
ScoreChanged(labScore2.Text); // This will reflect back to FMain labScore.Text
lista[indice] = new Koby(n, s);
indice++;
muestraLista(ref lstJugadores);
txtNombre.Clear();
txtNombre.Enabled = false;
}
}
So, your final code behind for your FMain2 would be:
public partial class FMain2 : Form
{
public delegate void ScoreChangedEvent(String score); // Event Handler Delegate
public event ScoreChangedEvent ScoreChanged; // Event Handler to subscribe to the Delegate
public FMain2()
{
InitializeComponent();
}
public void btnIntroducir_Click(object sender, EventArgs e)
{
try
{
string n = txtNombre.Text;
int s = int32.Parse(labScore2.Text);
ScoreChanged(labScore2.Text); // This will reflect back to FMain labScore.Text
lista[indice] = new Koby(n, s);
indice++;
muestraLista(ref lstJugadores);
txtNombre.Clear();
txtNombre.Enabled = false;
}
}
}