使用C#和winform开发一个登录界面,要求限制用户只能有三次登录机会
我的已经实现的代码如下
三次登录机会如何实现
```c#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WareHouseManagSys
{
public partial class Form1 : Form
{
public static string thisStr = @"Data Source=.; Database = mydatabase; Integrated Security=true";
public Form1()
{
InitializeComponent();
}
//登陆
private void button2_Click(object sender, EventArgs e)
{
SqlConnection thisConnect = new SqlConnection(thisStr);
SqlCommand cmd = new SqlCommand("login_proc", thisConnect);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@user", textBox1.Text);
cmd.Parameters.AddWithValue("@pws", textBox2.Text);
SqlParameter par = cmd.Parameters.Add("@status", SqlDbType.Int); //定义输出参数
par.Direction = ParameterDirection.Output; //参数类型为Output
thisConnect.Open();
cmd.ExecuteNonQuery();
switch ((int)par.Value)
{
case 0:
//MessageBox.Show("登陆成功!");
this.Hide();
Form2 f2 =new Form2();
f2.Show();
break;
case 1:
MessageBox.Show("账号不存在!请重新输入");
break;
case 2:
MessageBox.Show("密码错误!请重新输入");
break;
}
thisConnect.Close();
thisConnect.Dispose();
}
}
}
```
代码中用变量保存登录次数不适用于多用户并发的情况,而且如果判断代码在客户端,则用户可以关闭客户端重新打开客户端来规避错误次数的限制。
建议使用数据库或者缓存,记录每个用户登录错误的次数,记录可以只有key和value,key是用户id,value是登录错误次数。如果登录错误,则次数加1,达到3则不让登录。如果登录成功,则次数清零或清除这条记录。
如果有用,望采纳,谢谢!
button2_Click里顶一个静态变量保存登录次数,或者定义个全局变量保存次数。登录失败的时候次数+1