Home > Software design >  Create a login form with enable/disable button
Create a login form with enable/disable button

Time:11-26

I learned how to have a textbox and when the value is empty the button is disabled and when I enter a value in the textbox the button is enabled.

Now I want to have a login form that contains one textbox (for username) and another textbox (for password), so here I learned how to code. But how should I write the code so that when the condition (both text boxes are empty) the button is disabled and when the condition is (both text boxes have values) the button is enabled.

CodePudding user response:

Try this:

    private void txtUserName_TextChanged(object sender, EventArgs e)
    {
        CheckFields();
    }

    private void txtPassword_TextChanged(object sender, EventArgs e)
    {
        CheckFields();
    }

    private void CheckFields()
    {
        btnLogin.Enabled = txtPassword.Text.Length == 0 || txtUserName.Text.Length == 0 ? false : true;
    }

I assume that your username textbox is named, txtUserName, and your password textbox is named, txtPassword. Also the login button is named, btnLogin. I recommend setting the btnLogin enabled property to false when the form first loads. You can set that in the form's Load event:

    private void Form1_Load(object sender, EventArgs e)
    {
        btnLogin.Enabled = false;
    }

CodePudding user response:

I think it would be better if you implement this logic on the client side (javascript), it is unnecessary to go to the server again and again for every text change.

you should add onclick function on username and password textboxes and implement the logic to check whether both have values then enable the button else disable it.

CodePudding user response:

You should add the TextChanged event for both boxes and have it be something like this:

private void CheckTextboxes(object sender, EventArgs e)
    {
        if (string.IsNullOrWhiteSpace(txtUsername.Text) || string.IsNullOrWhiteSpace(txtPassword.Text)) 
        {
            button.Enabled = false;
            return;
        }
        button.Enabled = true;
    }

private void txtUsername_TextChanged(object sender, EventArgs e)
    {
        CheckTextboxes();
    }

private void txtPassword_TextChanged(object sender, EventArgs e)
    {
        CheckTextboxes();
    }

That way you ensure that if the user enters values on the textboxes in either order the button only enables if both have actual text written on them.

  • Related