【问题标题】:How to enable button after all textboxes are not empty in c# winforms?c#winforms中所有文本框都不为空后如何启用按钮?
【发布时间】:2021-07-03 17:19:43
【问题描述】:

在我的所有文本框都不为空之后,如何将按钮属性设置为 enabled=true? 我正在学习编程,我的应用程序很简单。

当我的一个文本框有文本时,我知道如何启用此属性,但事实并非如此。

用例是用户需要在两个文本框中输入数据,然后才能点击 btn。 如何以最简单的方式验证所有表单然后启用按钮?

只有 2 tb: https://i.imgur.com/JUslNWE.png

【问题讨论】:

  • 作为一个选项,您可以使用单个事件处理程序处理所有TextBox 控件的Validating 事件并检查它们是否为空,然后启用Button
  • @RezaAghaei 我该怎么做?这是行不通的。私人无效 generateHashBtn_Validating(object sender, System.ComponentModel.CancelEventArgs e) { if (loginTextBox.Text != String.Empty && passTextBox.Text != String.Empty) { generateHashBtn.Enabled = true; } }

标签: c# winforms button textbox


【解决方案1】:

您需要创建一个TextBox_TextChanged 事件并订阅所有文本框。

private void TextBox_TextChanged(object sender, EventArgs e)
{
    int notEmptyTextBoxCount = 0;
    int textBoxCount = 0;
    foreach (var item in Controls)
    {
        if (item is TextBox txtb)
        {
            textBoxCount++;
            if (txtb.Text != String.Empty)
                notEmptyTextBoxCount++;
        }
    }
    if (textBoxCount == notEmptyTextBoxCount)
        button.Enabled = true;
    else
        button.Enabled = false;
}

【讨论】:

  • button.Enabled = !this.Controls.OfType<TextBox>().Where(x => string.IsNullOrEmpty(x.Text)).Any();
【解决方案2】:

感谢大家的反馈。

我已经设法做到了:

private void ValidateTextBoxes()
    {
        if (loginTextBox.Text.Length != 0 && passTextBox.Text.Length != 0)
        {
            generateHashBtn.Enabled = true;
        }
        else
        {
            generateHashBtn.Enabled = false;
        }
    }

    private void TextBox1_TextChanged(object sender, EventArgs e)
    {
        ValidateTextBoxes();
    }

    private void TextBox2_TextChanged(object sender, EventArgs e)
    {
        ValidateTextBoxes();
    }

【讨论】:

  • 如果有人在 box1 中写入,然后在 box2 中写入,则启用该按钮。如果他们删除了 box1 或 box2 中的内容,该按钮将保持启用状态。
  • 感谢@LarsTech。我已经编辑了我以前的帖子。
猜你喜欢
  • 1970-01-01
  • 2017-08-23
  • 1970-01-01
  • 1970-01-01
  • 2020-10-21
  • 1970-01-01
  • 2020-09-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多