Reputation: 667
I wanna keep my program information updated, so I've been using the same method over and over again in each of these text changed method
private void textBox5_TextChanged(object sender, EventArgs e)
{ //specific code for textBox5
updatedatamethod(); }
private void textBox6_TextChanged(object sender, EventArgs e)
{ //specific code for textBox6
updatedatamethod(); }
private void textBox7_TextChanged(object sender, EventArgs e)
{ //specific code for textBox7
updatedatamethod(); }
private void textBox8_TextChanged(object sender, EventArgs e)
{ //specific code for textBox8
updatedatamethod(); }
etc...
I have the feeling this is a very crude way to program, since I'm not a native programmer I'm wondering if there's a technical more simple way to do it.
Note that I don't want all the text boxes to do the updatedatamethod, but only some of them
Edit: working on winforms
Edit2: some users marked this as a duplicate and posted a link, I understand it, but I don't agree. I don't wanna do only the updatedatamethod
i posted on my example, I also wanna do other specific button code besides that. The answer linked as a duplicate, assumes you wanna do the exactly same thing and nothing else on every item.
Upvotes: 1
Views: 131
Reputation: 223412
Simplest would be to attach a single event handler to all the textboxes' Click
event like:
textBox5.Click +=textBox_TextChanged;
textBox6.Click +=textBox_TextChanged;
textBox7.Click +=textBox_TextChanged;
in that event handler you can do:
EDIT: If you want to do some specific task related to each TextBox
, then you can cast the sender as TextBox
and compare it against your TextBoxes. like:
void textBox_TextChanged(object sender, EventArgs e)
{
TextBox textBox = sender as TextBox;
if (textBox == null)
{
return;//log or show message
}
if (textBox == textBox5)
{
//Specific for TextBox5
}
if (textBox == textBox6)
{
//Specific for TextBox6
}
updatedatamethod();
}
You can do that in the constructor after initializing your controls.
Upvotes: 2