简体   繁体   中英

Checking textBox in Windows Forms

I'm pretty new to Windows Forms and i have a button to continue and three textboxes. The button is disabled. Now the User first has to fill in all three textboxes before the button is enabled.

Please Help me.

Thank you.

您可以向所有文本框添加TextChanged事件,在处理程序中检查是否填充了所有三个文本框,如果是 -> 按钮已启用。

This will do the trick.

Wire up some methods to the TextChanged event of the text boxes (this can be done in the designer) but I have put it in the constructor of the form under InitializeComponent();

public Form1()
{
    InitializeComponent();

    textBox1.TextChanged += TextBox_TextChanged;
    textBox2.TextChanged += TextBox_TextChanged;
    textBox3.TextChanged += TextBox_TextChanged;
}

Then my method for the text changed simply calls a validation method and enables the button if this method returns true.

private void TextBox_TextChanged(object sender, EventArgs e)
{
      button1.Enabled = ValidateTextBoxes();
      //Anything else you might want to do...
}

and finally my method for validation. Pretty simple again if any of the text boxes are empty return false.

private bool ValidateTextBoxes()
{
    if (string.IsNullOrEmpty(textBox1.Text) || string.IsNullOrEmpty(textBox2.Text)
            || string.IsNullOrEmpty(textBox3.Text))
    {
       return false;
    }

    //Any other validation you may want... e.g length, regex pattern etc.

    return true;
}

You can use TextChange event for this purpose and use the same method on all the textboxes like - 在此处输入图片说明

And check like this

private void textBox1_TextChanged(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(textBox1.Text) && !string.IsNullOrEmpty(textBox2.Text))
            {
                button1.Enabled = true;
            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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