如何在填写整个表单时启用禁用按钮(C#)
我想在填写完整个表单后启用我的如何在填写整个表单时启用禁用按钮(C#),c#,C#,我想在填写完整个表单后启用我的按钮。我应该使用什么代码 这是一个windows窗体应用程序 if (textBox1!= null && textBox2 != null && textBox3 != null && textBox4 != null && textBox5 != null && textBox6 != null && textBox7 != null && textB
按钮
。我应该使用什么代码
这是一个windows窗体应用程序
if (textBox1!= null && textBox2 != null && textBox3 != null && textBox4 != null && textBox5 != null && textBox6 != null && textBox7 != null && textBox8 != null && textBox9 != null && textBox10 != null)
{
button2.Enabled = true;
}
else
{
button2.Enabled = false;
}
对所有文本框使用RequiredFieldValidation 例如:
将按钮
Enabled=false
属性设置为false。填写完所有文本框后,将其设置为启用=true您必须检查文本框内容,如下所示
if (textBox1.Text.Trim() != string.Empty && textBox2.Text.Trim() != string.Empty)
{
button2.Enabled = true;
}
else
{
button2.Enabled = false;
}
更新:您也可以使用下面Sergey Berezovskiy提到的String.IsNullOrEmpty方法您可以在WPF应用程序中订阅表单名为“Loaded”的事件,或在windows表单应用程序中订阅名为“Load”的事件。//使用文本框的文本更改事件并调用updateuserinterface方法,如:
private void OnTextChanged(object sender, EventArgs args)
{
UpdateUserInterface();
}
private void UpdateUserInterface()
{
if (textBox1!= null && textBox2 != null && textBox3 != null && textBox4 != null && textBox5 != null && textBox6 != null && textBox7 != null && textBox8 != null && textBox9 != null && textBox10 != null)
{
button2.Enabled = true;
}
else
{
button2.Enabled = false;
}
}
假设您使用的是WinForms,并且只有
TextBox
控件,您可以尝试以下操作:
button2.Enabled = true;
foreach (var testBox in this.Controls.OfType<TextBox>())
{
if (string.IsNullOrEmpty(textBox.Text))
{
button2.Enabled = false;
break;
}
}
button2.Enabled=true;
foreach(此.Controls.OfType()中的var testBox)
{
if(string.IsNullOrEmpty(textBox.Text))
{
按钮2.Enabled=false;
打破
}
}
还有更简洁的版本:
button2.Enabled = !this
.Controls
.OfType<TextBox>()
.Any(t => string.IsNullOrEmpty(t.Text));
button2.Enabled=!这
.控制
第()类
.Any(t=>string.IsNullOrEmpty(t.Text));
尽管有很多方法可以做到这一点,但有一种简单的方法是这样的,请注意,您的文本框控件不应位于容器中控件,如分组框或面板:
button2.Enabled = this.Controls.OfType<TextBox>().All(c => c.Text.Length != 0);
button2.Enabled=this.Controls.OfType().All(c=>c.Text.Length!=0);
我假设您使用的是WinForms您所尝试的有什么问题?为什么不使用必需的字段验证器?我不知道为什么人们试图回答这个问题而不回答@SergeyBerezovskiy的问题。有一个方法String.IsNullOrWhiteSpace
@Sergey Berezovskiy,同意。尝试将此代码放入form_load函数,但无效。。。我应该在哪里输入这个code@user3164631我真的猜不出你想要实现什么。只要把它放在任何你想要的地方,它就能达到你想要的效果。例如,如果要实时控制按钮,请使用此代码创建一个私有函数,并从每个文本框的“TextChanged”事件调用它。@Brain真的吗?textBox1!=空
零件和其他“已工作”?
button2.Enabled = this.Controls.OfType<TextBox>().All(c => c.Text.Length != 0);