-1

I'm currently stuck on the following: I have ~500 textboxes which I want to display information when clicked, however doing this seperately for each textbox would take way too long.

I have tried the following, using an array which contains all textboxes in my WinForm. However, I can't seem to get it to work.

  var textBoxes = new List<Control>();
            foreach (Control c in Controls)
            {
                if (c is TextBox)
                {
                    textBoxes.Add(c);
                }
            }

foreach(var c in textBoxes)
{ c.Click += textBox_Click();
}

public void textBox_Click(object sender, EventArgs e)
{ string location = c.Text;
MessageBox.Show(location);
}

I hope that someone can help me out, thanks!

DKT
  • 39
  • 6
  • 5
    **Why** do you have 500 textboxes in the first place? Were all those textboxes added and configured _by hand_? ...or by code-gen? If they were code-gen'd why can't you codegen also wire-up event-handlers? – Dai Dec 16 '21 at 10:07
  • "However, I can't seem to get it to work." - you need to show us how you created and populated your `textBoxes` collection. – Dai Dec 16 '21 at 10:08
  • 4
    _c.Click += textBox_Click();_ is wrong, it should be _c.Click += textBox_Click;_ – Steve Dec 16 '21 at 10:11
  • @Dai It is a visual representation of a warehouse, first row was handplaced, rest was copy pasted. Each textbox here represents a shelf in this warehouse. – DKT Dec 16 '21 at 10:17
  • A label might make more sense – Charlieface Dec 16 '21 at 10:26
  • `foreach (Control c in Controls)` – Dai Dec 16 '21 at 10:34

1 Answers1

1

To get all controls of a certain type and assign an event you can do this

foreach ( TextBox tb in this.Controls.OfType<TextBox>()) 
{
    tb.Click += textBox_Click;   //Note there are no brackets ()     
}

Then you don't need to create a separate array to store them (although that works too, and might be useful elsewhere).

Then you need to amend your click event as there is a problem here, so you need to cast the sender to a TextBox type like this.

 public void textBox_Click(object sender, EventArgs e)
 {
            string location = ((TextBox)sender).Text;
            MessageBox.Show(location);
 }
jason.kaisersmith
  • 7,807
  • 3
  • 26
  • 45