数组作为我的登录凭证(for循环)

本文关键字:for 循环 凭证 登录 我的 数组 | 更新日期: 2023-09-27 18:12:56

我对这些都不太熟悉。无论如何,我希望你们能帮助我一点,所以这是我目前的代码:

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!";
                }
            }
        }

由于某些原因,每当我输入错误的用户名和密码时,它显示:

if (textBox1.Text == usernames[i] && textBox2.Text == "password") 
An unhandled exception of type 'System.IndexOutOfRangeException' occurred in WindowsFormsApplication2.exe

如果有更好的方法来编写这个代码(简单得多就好了)。请不要犹豫,发布您自己的代码。我只需要一个登录表单使用数组!非常感谢!

数组作为我的登录凭证(for循环)

它将尝试检查每个用户。因为你有2个,它应该循环2次,但是没有。当

使用。length时
for (int i = 0; i <= usernames.Length; i++)
            {...}

运行3次,长度= 21代表0另一个是1另一个为2

由于您没有用户名[2](以0开头),它将发出一个错误,因为您正在尝试访问一个不存在的索引。

试试这个:

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

只能运行两次。(i <Array.length)>

试试这个

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!";
            }
        }
    }
}