最近看见好多人都在写这个,但他们用的都是用户名登录,如果用户名太长,那就太麻烦了。
第一步:按照网上的教程建表。并在表中手动输入一条数据。
第二步:在Form1.cs(登录界面)自定义一个判断密码用户名是否正确的方法:
public int Ex(string sql)
{
SqlCommand com = new SqlCommand(sql, conn);
if (conn.State == ConnectionState.Closed)
conn.Open();
com.CommandType = CommandType.Text;
int result = Convert.ToInt32(com.ExecuteScalar());
conn.Close();
return result;
}
再定义一个GetDataSet方法,用于查询用户名。
public static DataSet GetDataSet(string sql1)
{
SqlDataAdapter sqlda = new SqlDataAdapter(sql1,conn);
DataSet ds = new DataSet();
sqlda.Fill(ds);
return ds;
}
ID输入框的代码如下
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (char.IsDigit(e.KeyChar) || (e.KeyChar == '\r' || (e.KeyChar == '\b')))
e.Handled = false;
else
e.Handled = true;
}
判断输入是否合理方法代码如下:
private bool ValidateInput()
{
if (textBox1.Text.Trim() == "")
{
MessageBox.Show("请输入登录账号");
}
else if (int.Parse(textBox1.Text.Trim()) > 65535)
MessageBox.Show("请输入正确的登录账号");
else if (textBox1.Text.Trim().Length > 5 && textBox2.Text.Trim() == "")
MessageBox.Show("请输入密码");
return true;
}
登录按钮事件代码如下:
if (ValidateInput())
{
try
{
if(conn.State == ConnectionState.Open)
{
conn.Dispose();
conn.Close();
}
int id = int.Parse(textBox1.Text.Trim());
string sql = "select count(*) from tb_User where ID=" + id + " and Pwd = '" + textBox2.Text + "'";
int num = Ex(sql);
if (num == 1)
{
UserID = int.Parse(textBox1.Text.Trim());
this.Hide();
Form2 Form21 = new Form2();
Form21.Show();
}
else
{
MessageBox.Show("用户Id或密码不正确");
}
}
catch(Exception ex)
{
MessageBox.Show("未能连接到服务器","提示");
}
}
别忘了在
public Form1()
{
InitializeComponent();
}
的下面添加
public static int UserID = 0;
public static SqlConnection conn = new SqlConnection(@"Data Source=DESKTOP-GNQACEJ\Gres;Integrated Security=True;DataBase=Server");
新建一个主窗体,在主窗体中写入代码:
public static string PeopleName;
private void Form2_Load(object sender, EventArgs e)
{
PeopleName = Form1.GetDataSet("select Name from tb_User where ID=" + Form1.UserID).Tables[0].Rows[0][0].ToString();
label1.Text = PeopleName + "\n(" + Form1.UserID + ")";
label2.Text = Form1.GetDataSet("select Text from tb_User where ID=" + Form1.UserID).Tables[0].Rows[0][0].ToString();
if(label1.Text.Trim().Length < 1)
{
label2.Text = "无个性签名";
}
}
程序最终运行效果:Form1
Form2