问题
I have a textbox in a Windows form, I have clear button which basically clears the text char by char(that is one by one not all at once), my problem is i want to add another textbox to this form and would like to control both the textboxes with clear button meaning the clear should only clear the textbox which i have selected or clicked on, i tried doing it but either i am able to clear both the textboxes simultaneously or clear only textbox my code for single textbox is
private void clearBtn_Click(object sender, EventArgs e)
{
string s = txtID.Text;
if (s.Length > 0) txtID.Text = s.Substring(0, s.Length - 1);
}

回答1:
You can set the which control has focus upon focus and then use that to see which one needs to be removed.
private Textbox SelectedTextBox;
protected void Form_Load(object sender, EventArgs e)
{
TextBox1.GotFocus += TextBox_GotFocus;
TextBox2.GotFocus += TextBox_GotFocus;
}
private void clearBtn_Click(object sender, EventArgs e)
{
if(this.SelectedTextBox == null) return;
string s = this.SelectedTextBox.Text;
if (s.Length > 0) this.SelectedTextBox.Text = s.Substring(0, s.Length - 1);
}
private void TextBox_GotFocus(object sender, EventArgs e)
{
this.SelectedTextBox = (Textbox)sender;
}
回答2:
private void clearBtn_Click(object sender, EventArgs e) {
sting textbox1text = textbox1.tostring();
string textbox2text = textbox2.tostring();
if (textbox1text.length > 0){
textbox1text = textbox1text.Remove(textbox1text.length - 1)
}
if (textbox2text.length > 0){
textbox2text = textbox2text.Remove(textbox1text.length - 1)
}
}
that will "backspace" one character of each textbox. if you want to do a clear on the one you last updated textbox, add this to each if statement
if (textbox2text.length > 0 && textbox2text == textbox2text)
that will check if the textbox was updated before it clears, it wont clear if it hasnt been updated
来源:https://stackoverflow.com/questions/22915188/clearing-two-textbox-text-either-one-which-is-selected