What I try to achieve is, that I first generate some buttons dynamically via a loop and then give each button its own click action, in C#.
But unfortunately only the last click event will be executed for all buttons. (Every button will print "Klick - 3")
How can I achieve that each button will print e.g. its own message?
So, when I click Button-0 it will display "Klick - 0", and so on.
Here a simple example:
public static void Main(string[] args){
Form form = new Form();
form.Location = new System.Drawing.Point(0,0);
form.Width = 300;
form.Height = 300;
List<Button> buttons = new List<Button>();
for(int i = 0; i < 3; i++)
{
buttons.Add(new Button());
buttons[i].Text = $"Button - {i}";
buttons[i].Location = new System.Drawing.Point(0,i*40);
form.Controls.Add(buttons[i]);
}
for(int i = 0; i < 3; i++)
{
buttons[i].Click += (s,e) =>
{
Console.WriteLine($"Klick - {i}");
};
}
// keeps the form from disappearing
Application.Run(form);
}
I also thought maybe I could put all those events separately into some event-list(?), so they could be executed from there, but no luck with that.
PS: I found out, I could put something like:
if(s==buttons[0])
into the Click-Event-Loop and continue with some else-ifs to have each button its own actions, but isn't there something more convenient? I mean everytime the click event is triggered it would have to cycle through all the ifs...