如果文本框为空,则禁用按钮

use*_*308 4 c# asp.net

嘿伙计们,我有一个快速简单的问题,我想你.我想知道我是否可以创建一个实时事件来检查文本框的值.我的意思是如果文本框为空,则按钮不可点击.我想除了验证在代码中执行此操作之外还有吗?到目前为止我被困在这里:

if (YourName.Text = null)
{
       SubmitButton.Enabled = "False";
}
Run Code Online (Sandbox Code Playgroud)

其中Yourname是文本框,SubmitButton是按钮:)

das*_*ght 6

System.String提供了一对便利函数调用IsNullOrEmptyIsNullOrWhiteSpace您可以使用用于测试各种字符串,看空到最终用户的:

if (string.IsNullOrWhiteSpace(YourName.Text)) {
    SubmitButton.Enabled = false; // <<== No double-quotes around false
} else {
    // Don't forget to re-enable the button
    SubmitButton.Enabled = true;
}
Run Code Online (Sandbox Code Playgroud)

即使对于完全由空白字符组成的字符串,这也会禁用该按钮,这在验证名称时是有意义的.

以上是相同的

SubmitButton.Enabled = !string.IsNullOrWhiteSpace(YourName.Text);
Run Code Online (Sandbox Code Playgroud)

比带有版本的版本短if.