Reputation: 81
Not sure how to select a textbox from multiple textboxes on a form and clear it on the click event of a button. For example, if we have multiple operand fields for a calculator and need to implement clear current field button, how do I implement it? Here is the code snippet I have so far.
private void button2_Click(object sender, EventArgs e)
{
foreach (Control t in this.Controls)
{
if (t is TextBox)
{
if (t.Focused)
{
t.Text = "";
}
}
}
}
Upvotes: 1
Views: 73
Reputation: 16966
One option could be subscribing to TextBox
LostFocus
event.
Declare a class field to hold the reference of active TextBox
.
private TextBox activeTextbox;
in Form_Load
event subscribe to TextBox
LostFocus
event.
textbox1.LostFocus += (se,ev) => activeTextbox = textbox1;
textbox2.LostFocus += (se,ev) => activeTextbox = textbox2;
Now in button click
event
private void button2_Click(object sender, EventArgs e)
{
if(activeTextbox != null)
{
activeTextbox.Text = "";
}
}
Upvotes: 2
Reputation: 15613
As Hari Prasad mentioned, the active TextBox will lose the focus as soon as user clicks on the button. So I suggest using Leave
event and an instance to detect which TextBox has been active before the button has been clicked.
private TextBox _tmpTextbox;
private void txt1_Leave(object sender, EventArgs e)
{
_tmpTextbox = txt1;
}
private void txt2_Leave(object sender, EventArgs e)
{
_tmpTextbox = txt2;
}
And for the button:
private void btnTest_Click(object sender, EventArgs e)
{
_tmpTextbox.Text = "";
}
In order to shortened the code, you can use one even handler for all the textboxes:
private void txt1_Leave(object sender, EventArgs e)
{
TextBox activeTextBox = (TextBox) sender;
_tmpTextbox = activeTextBox;
}
Upvotes: 0