界面如下图
数据库信息
实现与数据库连接,判断输入的用户名和密码是否存在。登陆成功后跳转新窗口,隐藏旧窗口。
还是通过视频展示一下
记录计算机学习的小视频-2
form1代码
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 LoginDemo
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void label2_Click(object sender, EventArgs e)
{
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
string username = textBoxUserName.Text.Trim(); //取出账号
string password = textBoxPassWord.Text.Trim(); //取出密码
//string connstr = ConfigurationManager.ConnectionStrings["connectionString"].ToString(); //读取连接字符串
string myConnString = "Data Source=.;Initial Catalog=Test;Persist Security Info=True;User ID=sa;Password=luoluoluo";
SqlConnection sqlConnection = new SqlConnection(myConnString); //实例化连接对象
sqlConnection.Open();//打开数据库
string sql = "select userid,password from usertable where userid = '" + username + "' and password = '" + password + "'"; //编写SQL命令
SqlCommand sqlCommand = new SqlCommand(sql, sqlConnection);
SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();
if (sqlDataReader.HasRows)
{
MessageBox.Show("WELCOME!", "notice", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); //登录成功
label1.Text = "Log in :" + username;
FormMain formMain = new FormMain(); //新窗体
formMain.Show();
this.Hide(); //隐藏原窗体
}
else
{
MessageBox.Show("FAILED!", "notice", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
sqlConnection.Close();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
form2 代码
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;
namespace LoginDemo
{
public partial class FormMain : Form
{
public FormMain()
{
InitializeComponent();
}
private void FormMain_Load(object sender, EventArgs e)
{
// TODO: 这行代码将数据加载到表“testDataSet.usertable”中。您可以根据需要移动或删除它。
this.usertableTableAdapter.Fill(this.testDataSet.usertable);
}
private void button1_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
这个实验我是跟着视频做的,感觉比上一个明确一点。了解了很多可视化操作的方法,构造界面也非常熟练了。就是在连接数据库的代码那里,反复理解了好几遍,理解是理解的,但要我自己写应该还是够呛。我会尽量将代码与其作用挂钩,做到能顺畅自如的使用。因为觉得视频展示更直观一点,就需要先上传到b站,所以要等审核。