Anjo Liwanag Anjo Liwanag - 1 month ago 9
C# Question

c# | Array as my login credentials (for loop)

I'm kind of new to all of these. Anyways I hope you guys could help me out a bit So here's my current code:

namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
string[] usernames = { "user1", "user2" };
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
for (int i = 0; i <= usernames.Length; i++)
{
if (textBox1.Text == usernames[i] && textBox2.Text == "password")
{
Form2 frm = new Form2();
frm.Show();
this.Hide();
break;
}
else
{
textBox1.Clear();
textBox2.Clear();
textBox1.Text = "Wrong credentials!";
}

}
}


For some reason whenever I input a 'wrong' username and password it shows:

if (textBox1.Text == usernames[i] && textBox2.Text == "password")

An unhandled exception of type 'System.IndexOutOfRangeException' occurred in WindowsFormsApplication2.exe


If there's a better way to code this (much simpler would be great). Please don't hesitate to post your own code. I just need a login form using arrays! Thanks a bunch!

Answer

It will try to check every users. since you have 2 it should loop 2 times but no. when you use .Length where

for (int i = 0; i <= usernames.Length; i++)
            {...}

it run 3 times for a length = 2 one for 0 another for 1 another for 2

since you do not have a username[2] (it start with 0) it will issue an error because you are trying to access and index that does not exists.

try this:

for (int i = 0; i < usernames.Length; i++)
{...}

to run only two times. use always this for (i < array.length) when you are using .length.

try this

namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        string[] usernames = { "user1", "user2" };
        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            bool wasFound = false;
            for (int i = 0; i < usernames.Length; i++)
                if (textBox1.Text == usernames[i] && textBox2.Text == "password")
                {
                    wasFound = true;
                    break;
                }

            if (wasFound)
            {
                Form2 frm = new Form2();
                frm.Show();
                this.Hide();
            }
            else
            {
                textBox1.Clear();
                textBox2.Clear();
                textBox1.Text = "Wrong credentials!";
            }

        }
    }
}