在 c# winform 中更改的文本上启用禁用按钮
我正在开发一个应用程序,其中搜索框中有一个按钮(就像 iTunes 中的一个).我想在文本框中有文本时启用取消按钮,并在文本框为空时禁用它.我尝试使用以下代码在文本框上使用 text_changed 事件,但它跳过了 if 条件.即使发件人也向我发送了正确的值,但我无法将其放入 if else 中.
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;
}
}
请帮忙
这里有一个简单的解决方案.
Here is a simple solution.
private void textBox1_TextChanged(object sender, EventArgs e)
{
this.button1.Enabled = !string.IsNullOrWhiteSpace(this.textBox1.Text);
}
当然,您必须在表单最初加载时设置 button.Enabled = false,因为文本框事件不会在启动时触发(对于当前为您的问题提供的所有答案均为 true).
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).