Setting a button enabled after all fields are filled in

George Tyrebyter 46 Reputation points
2023-02-02T22:46:08.0566667+00:00

I have a window with three textboxes and a button. Is there a way to check if all fields have a value in each before setting the button enabled. It matters not what is in each box, rather each box has an entry.

Thanks

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,247 questions
0 comments No comments
{count} votes

Accepted answer
  1. Reza Aghaei 4,936 Reputation points MVP
    2023-02-02T23:45:54.88+00:00

    The easiest is setting the button as disabled first, then handling TextChanged event of all text boxes with the same handler and enable the button only if all those text boxes have value:

    using System;
    using System.Windows.Forms;
    
    namespace WindowsFormsApp1
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
                button1.Enabled = false;
                textBox1.TextChanged += TextBox_TextChanged;
                textBox2.TextChanged += TextBox_TextChanged;
                textBox3.TextChanged += TextBox_TextChanged;
            }
    
            private void TextBox_TextChanged(object sender, EventArgs e)
            {
                button1.Enabled = !string.IsNullOrEmpty(textBox1.Text)
                    && !string.IsNullOrEmpty(textBox2.Text)
                    && !string.IsNullOrEmpty(textBox3.Text);
            }
        }
    }
    
    2 people found this answer helpful.

0 additional answers

Sort by: Most helpful