[英]Enable disable button on text changed in c# winform
I am developing an application, in which there is a button in search box (like one in itunes).我正在开发一个应用程序,其中搜索框中有一个按钮(就像 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.
我尝试使用以下代码在文本框上使用 text_changed 事件,但它跳过了 if 条件。 Even sender sends me correct values but i am unable to put it into if else.
即使发件人向我发送了正确的值,但我无法将其放入 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请帮忙
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).当然,您必须在表单最初加载时设置 button.Enabled = false,因为文本框事件不会在启动时触发(对于当前为您的问题提供的所有答案,均为 true)。
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (String.IsNullOrEmpty(textBox1.Text))
btn_cancel.Visible = false;
else
btn_cancel.Visible = true;
}
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 sender.ToString()
将始终返回System.Windows.Forms.TextBox
您需要将sender
为TextBox
并使用Text
值作为您的 null 或空检查
尝试将发件人强制转换为 TextBox :
if (string.IsNullOrEmpty(((TextBox)sender).Text))
一个班轮:
btn_cancel.Visible = textBox1.Text.Length > 0;
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
.这并不假设事件源是一个特定的控件,并且如果错误地将它附加到不是
TextBox
东西上,则会避免异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.