Question

I'm trying to create a simple login screen, which has 2 textboxes and 1 button. When strings i've insterted in the first textbox (username) and the second textbox (password) matches the strings i've defined before, the buttons Enabled propertie should become True and when clicked, it should open another form, here's the code i've written so far:

public partial class LogInScreen : Form
{
    public LogInScreen()
    {
        InitializeComponent();
        string lietotajvards = "user";
        string parole = "user";
        if (textBox1.Text == lietotajvards && textBox2.Text == parole)
        {
            button1.Enabled = true;
        }
        else
        {
            button1.Enabled = true;
        }
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Form1 f1 = new Form1();
        this.Hide();
        f1.Show();
    }
}

The thing is that with my code it doesn't work as expected and the button is enabled all the time. Where's the problem?

Was it helpful?

Solution

Your code will only execute once when the form is initialized, you have to make use of a textchanged event on textbox1 and textbox2, thereafter you can use the code you wrote to check if the button needs to be enabled. In the else you must disable the button.

Text changed event handlers:

void textBox1_TextChanged(object sender, EventArgs e)
{
    handleLoginButton();
}

void textBox2_TextChanged(object sender, EventArgs e)
{
    handleLoginButton();
}

Enable/disable button:

private void handleLoginButton(){
        string lietotajvards = "user";
        string parole = "user";

        if (textBox1.Text == lietotajvards && textBox2.Text == parole)
        {
            button1.Enabled = true;
        }
        else
        {
            button1.Enabled = false;
        }
}

OTHER TIPS

The constructor only runs once for the form, you need to handle the text changed events for the input controls and then re-evaluate your condition again.

Also it should go without saying (although it is being said here) that this is a terrible way to handle logging in to an application.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top