简体   繁体   English

如何在 c# winforms 中的所有文本框不为空后启用按钮?

[英]How to enable button after all textboxes are not empty in c# winforms?

How can I make button property set to enabled=true after all my textboxes are not empty?在我的所有文本框都不为空之后,如何将按钮属性设置为 enabled=true? I'm learning programming and my apps are simple.我正在学习编程,我的应用程序很简单。

I know how to enable this property when one of my textboxes have text but this is not the case.当我的一个文本框有文本时,我知道如何启用此属性,但事实并非如此。

Use case is that user need to put data in both textboxes and after that will be able to click btn.用例是用户需要将数据放入两个文本框中,然后才能单击 btn。 How in most simple way can I validate all form and then enable button?如何以最简单的方式验证所有表单然后启用按钮?

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

You need to create a TextBox_TextChanged event and subscribe to all text boxes.您需要创建一个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;
}

Thanks guys for all feedback.感谢大家的所有反馈。

I have managed to do this this way:我设法做到了这种方式:

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();
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM