1.打开Microsoft Visual Studio新建C#窗体应用程序,命名为login
2.修改窗体的Text属性,添加控件Label、TextEdit(ps:注意设置Name属性以及位置的调整),然后添加控件SimpleButton(ps:控件前的图片通过Image属性设置),效果如下:
3.在项目中添加类,命名为DemoCls,代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace login
{
class DemoCls
{
public string sqlSelect()
{
return "OK";
}
}
}
4.添加按钮确定的点击事件,添加用户和密码TextEdit的KeyDown事件,代码如下(ps:数据库根据自己的本地数据库进行设置):
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 login
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnOK_Click(object sender, EventArgs e)
{
string conn = "server=.;database=数据库名字;user id = 用户名;password=密码";
SqlConnection con = new SqlConnection(conn);
con.Open();
SqlDataAdapter sqlDa = new SqlDataAdapter("select * from tb_stu", con);
DataTable dt = new DataTable();
sqlDa.Fill(dt);
MessageBox.Show(dt.Rows[0][1].ToString());
//调用类DemoCls中的sqlSelect方法
DemoCls my1 = new DemoCls();
MessageBox.Show(my1.sqlSelect());
}
//当用户第一个文本框输入信息完毕时按下Enter键自动聚焦到密码输入框
private void txtUser_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
txtPWD.Focus();
}
}
//当用户第二个文本框输入信息完毕按下Enter键相当于click确认按钮
private void txtPWD_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
btnOK_Click(sender, null);
}
}
}
}