-3

Im coding in a windowsformapplication, c# This is what i have done so far

    List<Button> list = new List<Button>();
    private void Form1_Load(object sender, EventArgs e)
    {

        for (int j = 0; j <= 13; j++)
        {
            for (int i = 0; i <= 13; i++)
            {
                Button ruta = new Button();
                ruta.Location = new Point(0+ (i * 50), 0 + (j * 50));
                ruta.Size = new Size(50, 50);
                ruta.AutoSize = false;
                ruta.Text = "";
                ruta.TabStop = false;
                list.Add(ruta);
                this.Controls.Add(ruta);
            }
        }
    }

What I now want is to be able to click on of these buttons and then change the text of a textbox to the index of the pressed button, I'm a real noob when it comes to C# so I have no idea what im doing atm. What i thought about was something like

     private void ruta_click(object sender, EventArgs e)
      {
        txtBox.text = list.SelectedItemIndex();
      }

which obviously wont work since SelectedItemIndex() isnt a real method but just an example.

c7nt
  • 11
  • 1

1 Answers1

2

You should look for the index of sender in your list. The sender will be the button that was clicked, and generally sender will be the control that triggered the event. Also don't forget to add the handler to the button as you do not do taht in your for right now.

private void Form1_Load(object sender, EventArgs e)
{

    for (int y = 0; y <= 13; y++)
    {
        for (int i = 0; i <= 13; i++)
        {
            Button ruta = new Button();
            ruta.Location = new Point(0 + (i * 50), 0 + (y * 50));
            ruta.Size = new Size(50, 50);
            ruta.AutoSize = false;
            ruta.Text = "";
            ruta.TabStop = false;
            ruta.Click += ruta_click;
            list.Add(ruta);
            this.Controls.Add(ruta);
        }
    }
}

private void ruta_click(object sender, EventArgs e)
{
    txtBox.Text = list.IndexOf((Button)sender) + "";
}
Titian Cernicova-Dragomir
  • 230,986
  • 31
  • 415
  • 357