Reputation: 101
Is there a way to create a class or something that can contain all these different textboxes. I just want to know if this is the most efficient way I can code this.
private void textBox1_Click(object sender, EventArgs e)
{
textBox1.Text = "";
}
private void textBox2_Click(object sender, EventArgs e)
{
textBox2.Text = "";
}
private void textBox3_Click(object sender, EventArgs e)
{
textBox3.Text = "";
}
private void textBox4_Click(object sender, EventArgs e)
{
textBox4.Text = "";
}
private void textBox5_Click(object sender, EventArgs e)
{
textBox5.Text = "";
}
Upvotes: 0
Views: 70
Reputation: 89051
You can add the event handler to all the TextBoxes on load, eg
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
foreach(var tb in this.Controls.OfType<TextBox>())
{
tb.Click += (sender, eventArgs) => ((TextBox)sender).Text = "";
}
}
Upvotes: 2
Reputation: 186668
Don't create separated event handlers for each TextBox
es. Instead, create a combined event for all the TextBoxes
: textBox1..textBox5
.
Then
private void textBoxs_Click(object sender, EventArgs e)
{
if (sender is TextBox box) box.Text = "";
}
Upvotes: 5