第一步
我在数据库中建了一个 test 数据库,在这个数据库下面建了一个 users 的表,用来存放用户名和密码。
值得注意的是,如果你要区分大小写,要在创建成功之前对其排序规则进行设定,也就是说设置之后再点保存,完成 users 表的创建
选择 ... 符号後,选择区分大小写, 确定 之后 保存表,命名为 users
第二步
把可以登录的用户名和密码输入进去,这时可以区分大小写了
代码Form1.cs, 这是登录窗体
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsFormsApp2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//使用try...catch语句返回try代码区异常
try
{
//创建数据库连接并打开
string ConString = "server=.;database=test;uid=sa;pwd=sa;";
SqlConnection ConUser = new SqlConnection(ConString);
string CmdString = string.Format($"select * from users " +
$"where " +
$"Id= '{textBox1.Text.Trim()}' and PassWord=" +
$"'{textBox2.Text.Trim()}' ");
//也就是说你在数据库test下面里一个users的表
SqlCommand cmdStudent = new SqlCommand(CmdString, ConUser);
ConUser.Open();
//创建读取对象SqlDataReader
SqlDataReader dtrStudent = cmdStudent.ExecuteReader();
//使用HasRows属性判断数读取的dtrStudent对象中是否有数据
if (dtrStudent.HasRows)
{
while (dtrStudent.Read())
{
this.DialogResult = DialogResult.OK;
this.Close(); //关闭登录窗口
}
}
else
{
MessageBox.Show("账号或密码错误,请重试!");
textBox1.Text = "";
textBox2.Text = "";
}
dtrStudent.Close();
ConUser.Close();
}
//返回异常
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
/// <summary>
/// 退出登录
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
代码Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsFormsApp2
{
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Form Login = new Form1();
Login.ShowDialog();//显示登陆窗体
if (Login.DialogResult == DialogResult.OK)
Application.Run(new Form2());//判断登陆成功时主进程显示Form2窗口
else return;
//Application.Run(new Form1());
}
}
}