问题
I am developing an application, in which there is a button in search box (like one in itunes). I want to enable cancel button whenever there is text in text box and disable it when text box is empty. I tried with text_changed event on textbox with the following code, but it jump over the if condition. Even sender sends me correct values but i am unable to put it into if else.
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(sender.ToString()))
{
btn_cancel.Visible = false;
}
else
{
btn_cancel.Visible = true;
}
}
Please help
回答1:
Here is a simple solution.
private void textBox1_TextChanged(object sender, EventArgs e)
{
this.button1.Enabled = !string.IsNullOrWhiteSpace(this.textBox1.Text);
}
Of course, you'll have to set the button.Enabled = false when the form initially loads since the textbox event won't fire on startup (true for all answers currently provided for your question).
回答2:
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (String.IsNullOrEmpty(textBox1.Text))
btn_cancel.Visible = false;
else
btn_cancel.Visible = true;
}
回答3:
Try this:
private void textBox1_TextChanged(object sender, EventArgs e)
{
var textbox = sender as TextBox;
if (string.IsNullOrEmpty(textbox.Text))
{
btn_cancel.Visible = false;
}
else
{
btn_cancel.Visible = true;
}
}
sender.ToString()
will always return System.Windows.Forms.TextBox
you need to cast sender
as TextBox
and use the Text
value for your null or empty check
回答4:
try casting the sender to TextBox :
if (string.IsNullOrEmpty(((TextBox)sender).Text))
回答5:
One liner:
btn_cancel.Visible = textBox1.Text.Length > 0;
回答6:
This is how I'd do it:
private void textBox1_TextChanged(object sender, EventArgs e)
{
string text = ((sender as TextBox) == null ? string.Empty : (sender as TextBox).Text);
this.button1.Enabled = (string.IsNullOrWhiteSpace(text) == false);
}
This doesn't assume the event source is a specific control and avoids an exception if by mistake it's attached to something that's not a TextBox
.
来源:https://stackoverflow.com/questions/14350987/enable-disable-button-on-text-changed-in-c-sharp-winform