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 = "";
}
CodePudding user response:
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 = "";
}
CodePudding user response:
The way I would do it:
First we create a function that receives a textbox object as a parameter:
public void CleanTextBox(System.Windows.Forms.TextBox TextBoxObj){
TextBoxObj.Text = "";
}
And after that, you can call this function wherever you need.
CodePudding user response:
You can add the event handler to all the TextBoxes on load, eg
protected override void onl oad(EventArgs e)
{
foreach(var c in this.Controls)
{
if (c is TextBox tb)
{
tb.Click = (sender, eventArgs) => ((TextBox)sender).Text = "";
}
}
base.OnLoad(e);
}