Reputation: 35
I am building a simple calculator. I have three textBoxes: textBox1 (first operand), textBox2 (second operand), and textBox3 (result). I have numerous operand functions that can be performed. I also have a button that will clear all fields, as well as other functions.
I am having difficulty with the code needed to delete the text in a specific textbox with a button only when the cursor is in that textbox.
Ex: if cursor is in textBox1, the button only clears that textbox.
Any help is much appreciated.
Thanks.
Upvotes: 0
Views: 1266
Reputation: 54433
When the Button
is clicked it will gain focus.
So you need to keep track of which of your TextBoxes
got focus last.
Create a class level variable for that:
TextBox focusedTextBox = null;
Now hook up this event with the Enter
event of all three TextBoxes
:
private void textBoxes_Enter(object sender, EventArgs e)
{
focusedTextBox = sender as TextBox;
}
Then this will only clear the one your user was in last:
private void buttonClearCurrent_Click(object sender, EventArgs e)
{
if (focusedTextBox != null) focusedTextBox.Text = "";
}
Upvotes: 2
Reputation: 746
You can use event: "MouseHover" or "MouseClick" and set textBox1.Text=""
Upvotes: 0
Reputation: 610
In this case you have to use the Focused property in the textbox. But you need to make a loop to identify which text box is focused.
like:
var focusedControl;
foreach(var control in this.Controls)
{
if(control is TextBox)
{
if(control.Focused)
{
focusedControl = control;
break;
}
}
}
Upvotes: 0