Reputation: 37
I have a form with alot of textboxes, and I have a function that I want to run when a value in any of the textboxes is changed. Is there a way to do the same thing for every textbox without duplicating the code for each and every textbox? Here's the code that works for one:
private void Team1Q2_TextChanged(object sender, EventArgs e)
{
int parsedValue;
if (!int.TryParse(Team1Q1.Text, out parsedValue))
{
Team1Q1.Text = "0";
return;
}
else
{
CalculateTotals();
}
}
Upvotes: 0
Views: 4166
Reputation: 2812
in Form_load
, assign the text_changed
event to all textboxes
foreach (Control item in this.Controls)
{
if (item.GetType() == typeof(TextBox))
(item as TextBox).TextChanged += Form6_TextChanged;
}
and then you can handle the all text_changed
event
void Form6_TextChanged(object sender, EventArgs e)
{
TextBox T = sender as TextBox;
//this is your detail
}
Upvotes: 0
Reputation: 938
Try like this...
private void TextBoxEventHandler_TextChanged(object sender, EventArgs e)
{
var entryField = sender as TextBox;
lblKeyedValue.Text = entryField.Text.ToUpper();
}
and Add this event handler into textbox(s) like below...
yourTextBoxName.TextChanged += new EventHandler(TextBoxEventHandler_TextChanged);
Upvotes: 0
Reputation: 15623
Just set all the TextChanged
events for your TextBoxes to Team1Q2_TextChanged
in design mode.
Upvotes: 1
Reputation: 2141
Team1Q2_TextChanged is just an event handler you created for one of the textboxes. You can use the same event handler for all the textboxes. You will have to set all the textboxes's changed events to the same event handler.
If you are setting up the eventhandlers in visual studio designer, just copy paste the same event handler for all.
If you are setting up the event handlers in C# code behind, you can do this
textBox1.TextChanged += new EventHandler(textBox_TextChanged);
textBox2.TextChanged += new EventHandler(textBox_TextChanged);
textBox3.TextChanged += new EventHandler(textBox_TextChanged);
If you see I am using the same event handler for all textboxes.
Upvotes: 0
Reputation: 12459
Register this event handler for all of your textboxes
, and cast the sender
object to use the event raiser textbox.
Code:
private void Team1Q2_TextChanged(object sender, EventArgs e)
{
TextBox senderTextBox = sender as TextBox;
int parsedValue;
if (!int.TryParse(senderTextBox.Text, out parsedValue))
{
senderTextBox.Text = "0";
return;
}
else
{
CalculateTotals();
}
}
Subscribing event handler:
txtbox1.TextChanged += Team1Q2_TextChanged;
txtbox2.TextChanged += Team1Q2_TextChanged;
txtbox3.TextChanged += Team1Q2_TextChanged;
//so on
Upvotes: 2