本次实验除了用到上节课学到的,最重要的就是连接数据库
我也是在这个地方出了问题,后来经过搜索成功解决
(具体操作:与 SQL Server 建立连接时出现与网络相关的或特定于实例的错误)
制作登录窗口,密码隐藏
点击取消退出程序,点击确定:
登陆失败弹窗
登陆成功弹窗
跳转到下一窗口并隐藏登录窗口
用DataGridView显示数据库中学生表信息
点击CLOSE按钮退出程序
以下为登录窗口代码:
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 Login
{
public partial class FormLogin : Form
{
public FormLogin()
{
InitializeComponent();
}
private void OK_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=1234";
SqlConnection sqlConnection = new SqlConnection(myConnString); //实例化连接对象
sqlConnection.Open();
string sql = "select NAME,PASSWORD from usertable where NAME = '" + 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 = "欢迎 " + username;
//Form2 form2 = new Form2();
//form2.Show();
//this.Hide();
FormMain formMain = new FormMain();
formMain.Show();
this.Hide();
}
else
{
MessageBox.Show("FAILED!", "notice", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
sqlConnection.Close();
}
private void Cancel_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}