首页 > 解决方案 > 当表单超过错误登录尝试次数时,我似乎无法关闭表单

问题描述

当表单超过错误登录尝试次数时,我似乎无法关闭表单我想知道当我的错误登录尝试次数超过 3 次时关闭表单的程序

       private void button1_Click(object sender, EventArgs e)
    {
        
        string nama = textBox1.Text;
        string pass = textBox2.Text;


        if (nama.Equals(pass) == true)
        {
            MessageBox.Show("login success");
        }
       
        else
        {
            MessageBox.Show("login failed");
            for (int i = 1; i<=3; i++)
            {
                MessageBox.Show("login amount exceeded");
                this.Close();
            }
        }

    }
}

}

标签: c#visual-studio

解决方案


您需要为button1_click事件之外的失败登录尝试设置一个计数器;否则,每次单击按钮时,您的变量都会重新初始化为 0。在您的代码中,您甚至没有在变量中跟踪它,您只是有一个 for 循环。所以你的代码应该是这样的:

int failedLoginAttemps = 0;


private void button1_Click(object sender, EventArgs e)
{
    
    string nama = textBox1.Text;
    string pass = textBox2.Text;

    //you can instead do this in C#: if (name == pass)
    if (nama.Equals(pass) == true)
    {
        //you probably want to reset the counter if successful
        failedLoginAttempts = 0;
        MessageBox.Show("login success");
    }
   
    else
    {
        //increment the counter here
        failedLoginAttempts ++; 

        MessageBox.Show("login failed");
        if(failedLoginAttempts >= 3)
        {
            MessageBox.Show("login amount exceeded");
            this.Close();
        }
    }

}

推荐阅读