-1

I want to perform a username and password check before allowing access to Form2. Form2 should only load if the name and password match. However, my code doesn't work and Form2 always loads. And also How can i close the first form when the second opens

 private void BtnLogin_Click(object sender, EventArgs e)
    {
        var newForm = new Form2();
        if (txtbName.Text = "Georgi"&& txtbPassword.Text = "123" )
        {
            newForm.Show();
        }
}
gmatinski
  • 41
  • 8

4 Answers4

0

You should use == (instead of =) to check. Obviously your code should not be used in a production application, storing passwords in code is not recommended.

   private void BtnLogin_Click(object sender, EventArgs e)
    {
        var newForm = new Form2();
        if (txtbName.Text == "Georgi" && txtbPassword.Text == "123" )
        {
            newForm.Show();
        }
   }
Murray Foxcroft
  • 12,785
  • 7
  • 58
  • 86
0

I think you can use bellow code. You should Use == to check for equality

private void BtnLogin_Click(object sender, EventArgs e)
{
   var newForm = new Form2();
   if (string.Equals(txtbName.Text.ToLower() , "Georgi".ToLower()) && string.Equals(txtbPassword.Text , "123"))
    {
      newForm.Show();
    }
}
Reza Jenabi
  • 3,884
  • 1
  • 29
  • 34
0
private void BtnLogin_Click(object sender, EventArgs e)
{
    var newForm = new Form2();
    if (string.Equals(txtbName.Text, "Georgi") && string.Equals(txtbPassword.Text, "123"))
    {
        newForm.Show();
    }
}

Use the above code. For comparing strings in c# it is better to use string.Equals instead of ==. Have a look at this.

Waleed Naveed
  • 2,293
  • 2
  • 29
  • 57
0

You can do string comparison, there are lot of samples available in Google:

    private void BtnLogin_Click(object sender, EventArgs e)
    {
        var newForm = new Form2();
        if (string.Equals(txtbName.Text ,"Georgi") &&string.Equals(txtbPassword.Text, "123" )
        {
            newForm.Show();
        }
   }

And this is for your reference C# | Equals(String, String) Method

Nimantha
  • 6,405
  • 6
  • 28
  • 69
Noorul
  • 873
  • 2
  • 9
  • 26