winform 没有优化过的登录退出代码
首先在Vs中创建Windows窗体应用
根据button按钮 lable TextBox分别将控件拉入页面,更改名字。双击登录进入页面
代码块如下
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.Threading.Tasks;
using System.Windows.Forms;
namespace WinStudent
{
public partial class FrmLogin : Form
{
public FrmLogin()
{
InitializeComponent();
}
private void FrmLogin_Load(object sender, EventArgs e)
{
}
/// <summary>
/// 登录系统
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnLogin_Click(object sender, EventArgs e)
{
//获取用户输入信息
string uName = txtUserName.Text.Trim();
string uPwd = txtUserPwd.Text.Trim();
//判断是否为空
if (string.IsNullOrEmpty(uName))
{
MessageBox.Show("请输入账号!", "登录提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtUserName.Focus();
return;
}
if (string.IsNullOrEmpty(uPwd))
{
MessageBox.Show("请输入密码!", "登录提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtUserPwd.Focus();
return;
}
//与数据库通信 检查输入与数据库中是否一致
{
//建立与数据库连接
string connString = "server=.;database=StudentNewDB;uid=sa;pwd=localhost;";
SqlConnection conn = new SqlConnection(connString);
//写查询语句 拼接式sql注入 推荐大家使用参数化sql
// string sql = "select count(1) from UserInfo where UserName='" + uName + "'and UserPwd='" + uPwd + "'";
string sql = "select count(1) from UserInfo where UserName=@UserName and UserPwd=@UserPwd";
//添加参数(如果参数特别多的情况下可以考虑使用数组)
//SqlParameter paraUName = new SqlParameter("@UserName", uName);
//SqlParameter paraPwd = new SqlParameter("@UserPwd", uPwd);
SqlParameter[] paras =
{
new SqlParameter("@UserName", uName),
new SqlParameter("@UserPwd", uPwd)
};
//创建Command
SqlCommand cmd = new SqlCommand(sql, conn);
//添加参数之前先清空;在添加
cmd.Parameters.Clear();
//单个的添加参数
//cmd.Parameters.Add(paraUName);
//cmd.Parameters.Add(paraPwd);
//数组多个添加参数
cmd.Parameters.AddRange(paras);
//打开连接
conn.Open();
//执行命令
object o = cmd.ExecuteScalar();//执行查询,返回结果集第一行第一列的值,忽略其他的行或列
//关闭数据库
conn.Close();
//处理结果
if (o == null || o == DBNull.Value || ((int)o) == 0)
{
MessageBox.Show("请登录账号或密码有错误,请检查", "登录提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
else
{
MessageBox.Show("登录成功", "登录提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
//跳转到主页面
}
}
//返回的结果进行不同的提示
}
/// <summary>
/// 退出
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnExit_Click(object sender, EventArgs e)
{
//this.Close();如果是主页面可以用这一条代码进行退出
Application.Exit();
}
}
}