实验反馈2

本次实验除了用到上节课学到的,最重要的就是连接数据库

我也是在这个地方出了问题,后来经过搜索成功解决
(具体操作:与 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();
        }
    }
}
原创文章 23 获赞 35 访问量 1万+

猜你喜欢

转载自blog.csdn.net/MooM_X/article/details/105956978