![](https://iknow-base.cdn.bcebos.com/lxb/notice.png)
我用C# Windows窗体做了一个小程序。想为其添加一个登录界面,不知道怎么写代码,求高手解答, 小弟感激不
登录界面:
后台代码:
//登录按钮单击事件
private void button1_Click(object sender, EventArgs e)
{
string loginname = this.txt_LoginName.Text;
string password = this.txt_PassWord.Text;
UserInfo model = new UserInfo();
model = UserInfoManager.GetUserInfoByuserName(loginname); //调用BLL里面的
if (model != null)
{
if (model.PassWord == password)
{
this.DialogResult = DialogResult.OK;
this.Close();
}
else
{
this.lb_massge.Text = "您输入的密码错误!";
}
}
else
{
this.lb_massge.Text = "您输入的用户名不存在!";
}
}
Bll:
namespace HIS.BLL
{
public class UserInfoManager
{
UserInfoService dal = new UserInfoService();
//根据用户名查询单条用户信息
public static UserInfo GetUserInfoByuserName(string userName)
{
return UserInfoService.GetUserInfoByuserName(userName); //调用DAL里面的
}
}
}
DAL:
/// <summary>
/// 根据用户名查询
/// </summary>
/// <returns></returns>
public static UserInfo GetUserInfoByuserName(string userName)
{
UserInfo userInfo = null;
string sql = "select * from userInfo where userName=@UserName";
SqlParameter[] spr = new SqlParameter[]{
new SqlParameter("@UserName",userName)};
SqlDataReader reader = DBHelper.DBHelper.Reader(sql, spr); //调用DBHelper里面的Reader方法
if (reader.Read())
{
userInfo = new UserInfo();
userInfo.UserId = Convert.ToInt32(reader["UserId"]);
userInfo.UserName = Convert.ToString(reader["UserName"]);
userInfo.PassWord = Convert.ToString(reader["PassWord"]);
userInfo.Email = Convert.ToString(reader["Email"]);
userInfo.ProtectPass = Convert.ToInt32(reader["ProtectPass"]);
}
reader.Close();
HIS.DBHelper.DBHelper.Connection.Close(); //调用DBHelper里面的Connection
return userInfo;
}
DBHelper:
/// <summary>
/// 获取全部的信息,带参数
/// </summary>
/// <param name="sql"></param>
/// <param name="spr"></param>
/// <returns></returns>
public static SqlDataReader Reader(string sql, SqlParameter[] spr)
{
SqlConnection conn = new SqlConnection(connString); //connString链接字符串
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddRange(spr);
SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
return reader;
}
//链接字符串
private static string connString = System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"].ToString(); //获取app.config里面的
private static SqlConnection connection = null;
//连接
public static SqlConnection Connection
{
get
{
connection = new SqlConnection(connString);
if (connection.State == ConnectionState.Closed)
connection.Open();
if (connection.State == ConnectionState.Broken)
{
connection.Close();
connection.Open();
}
return connection;
}
}
自己建一个配置文件:
app.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="ConnectionString" value="Data Source=.;Initial Catalog=数据库名称;User ID=用户名;Password=密码" />
</appSettings>
</configuration>
祝你好运!