C#学生信息管理系统-代码展示

编程环境:SQL Server 2019
Visual Studio 2019

(仅功能代码)

  • 登陆
    C#学生信息管理系统-代码展示_第1张图片
private void button2_Click(object sender, EventArgs e)  //登陆
        {
            
                string username = textBoxUserName.Text.Trim();  //取出账号
                string password = EncryptWithMD5(textBoxPassWord.Text.Trim());  //取出密码
                name  =  username;
            
                //string connstr = ConfigurationManager.ConnectionStrings["connectionString"].ToString(); //读取连接字符串
                string myConnString = "Data Source=.;Initial Catalog=Text;Persist Security Info=True;User ID=sa;Password=110023";  //连接字符串 Data source为服务器的名字  Text为连接的库

                SqlConnection sqlConnection = new SqlConnection(myConnString);  //实例化连接对象
                sqlConnection.Open();

                string sql = "select UserID,UserPassword from UserMessage where UserID = '" + username + "' and UserPassword = '" + password + "'";                                            //编写SQL命令
               
                SqlCommand sqlCommand = new SqlCommand(sql, sqlConnection);
                SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();
            
             string select_by_id="select * from UserMessage where UserID='" + username+"'";
            
            if (sqlDataReader.HasRows && radioButton1.Checked && txtVerifyCode.Text.Equals(VerifyCode, StringComparison.OrdinalIgnoreCase))        //学生成功登录
            {
                MessageBox.Show("欢迎使用!");             //登录成功
                FormStudent formstudent = new FormStudent();
                formstudent.Show();
                //this.Hide();
            }
            if (sqlDataReader.HasRows && radioButton2.Checked && txtVerifyCode.Text.Equals(VerifyCode, StringComparison.OrdinalIgnoreCase))      //管理员成功登录
            {
                MessageBox.Show("欢迎使用!");             //登录成功
                FormAdmini formAdmini = new FormAdmini();
                formAdmini.Show();
                // this.Hide();
            }

            if (textBoxUserName.Text.Trim() == "")
            {
                MessageBox.Show("请输入学号/工号!");
            }
            if (textBoxPassWord.Text.Trim() == "")
            {
                MessageBox.Show("请输入密码!");
            }
            //验证码
            if (string.IsNullOrEmpty(txtVerifyCode.Text))
            {
                MessageBox.Show("请输入验证码!");
                return;
            }
            if (sqlDataReader.HasRows )
                {
                //label1.Text = "Log in :" + username;
                if (txtVerifyCode.Text.Equals(VerifyCode, StringComparison.OrdinalIgnoreCase))
                {
                    label1.Text = "Log in :" + username;

                }
                else
                {
                    MessageBox.Show("验证码错误!请重新输入!");
                }
            }
                else if(!sqlDataReader.Read() && textBoxPassWord.Text.Trim() !="" && textBoxUserName.Text.Trim() != "")
                {
                    MessageBox.Show("密码输入错误!", "notice", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                sqlConnection.Close();
            
        }

验证码

private string MakeCode(int codeLen)
        {
            if (codeLen < 1)
            {
                return string.Empty;
            }

            int number;
            string checkCode = string.Empty;
            Random random = new Random();

            for (int index = 0; index < codeLen; index++)
            {

                number = random.Next();

                if (number % 2 == 0)
                {
                    checkCode += (char)('0' + (char)(number % 10));     //生成数字
                }
                else
                {
                    checkCode += (char)('A' + (char)(number % 26));     //生成字母
                }
            }

            return checkCode;
        }
        private Image CreateCodeImg(string checkCode)
        {
            if (string.IsNullOrEmpty(checkCode))
            {
                return null;
            }

            Bitmap image = new Bitmap((int)Math.Ceiling((checkCode.Length * 12.5)), 22);

            Graphics graphic = Graphics.FromImage(image);

            try
            {
                Random random = new Random();

                graphic.Clear(Color.White);

                int x1 = 0, y1 = 0, x2 = 0, y2 = 0;

                for (int index = 0; index < 25; index++)
                {
                    x1 = random.Next(image.Width);
                    x2 = random.Next(image.Width);
                    y1 = random.Next(image.Height);
                    y2 = random.Next(image.Height);

                    graphic.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
                }

                Font font = new Font("Arial", 12, (FontStyle.Bold | FontStyle.Italic));
                LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Red, Color.DarkRed, 1.2f, true);
                graphic.DrawString(checkCode, font, brush, 2, 2);

                int x = 0;
                int y = 0;

                //画图片的前景噪音点
                for (int i = 0; i < 100; i++)
                {
                    x = random.Next(image.Width);
                    y = random.Next(image.Height);

                    image.SetPixel(x, y, Color.FromArgb(random.Next()));
                }

                //画图片的边框线
                graphic.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);

                return image;

            }
            finally
            {
                graphic.Dispose();
            }
        }
        private void pictureBox1_Click(object sender, EventArgs e)
        {
            VerifyCode = MakeCode(5);
            pictureBox1.Image = CreateCodeImg(VerifyCode);
        }

密码加密

public static string EncryptWithMD5(string source)      //MD5加密
        {
            byte[] sor = Encoding.UTF8.GetBytes(source);
            MD5 md5 = MD5.Create();
            byte[] result = md5.ComputeHash(sor);
            StringBuilder strbul = new StringBuilder(40);
            for (int i = 0; i < result.Length; i++)
            {
                strbul.Append(result[i].ToString("x2"));//加密结果"x2"结果为32位,"x3"结果为48位,"x4"结果为64位
            }
            return strbul.ToString();
        }
  • 注册
    C#学生信息管理系统-代码展示_第2张图片
private void buttonOK_Click(object sender, EventArgs e)//注册成功
        {
            try
            {
                string connString = "Data Source =.; Initial Catalog = Text;  Persist Security Info = True;User ID = sa; Password =110023";//数据库连接字符串
                SqlConnection connection = new SqlConnection(connString);//创建connection对象
                string sql = "insert into UserMessage (UserName, UserID ,   UserPassword, UserIdentity ,UserSex, UserNumber ,UserBirthday ,UserPhoto ) " +
                                                        "values (@username, @userid, @userpassword,@useridentity,@usersex,@usernumber,@userbirthday,@userphoto)";
                SqlCommand command = new SqlCommand(sql, connection);

                
                SqlParameter sqlParameter = new SqlParameter("@userid", textBoxNum.Text);
                command.Parameters.Add(sqlParameter);
                sqlParameter = new SqlParameter("@username", textBoxName.Text);
                command.Parameters.Add(sqlParameter);
                sqlParameter = new SqlParameter("@userpassword", EncryptWithMD5(textBoxPassword.Text));
                command.Parameters.Add(sqlParameter);
                sqlParameter = new SqlParameter("@usersex", comboBoxsex.Text);
                command.Parameters.Add(sqlParameter);
                sqlParameter = new SqlParameter("@usernumber", textBoxNumber.Text);
                command.Parameters.Add(sqlParameter);
                sqlParameter = new SqlParameter("@userbirthday", dateTimePickerbirth.Value);
                command.Parameters.Add(sqlParameter);
                sqlParameter = new SqlParameter("@useridentity", comboBoxidentity.Text);
                command.Parameters.Add(sqlParameter);
                sqlParameter = new SqlParameter("@userphoto", SqlDbType.VarBinary, mybyte.Length, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, mybyte);
                command.Parameters.Add(sqlParameter);
               
                //打开数据库连接
                connection.Open();
                command.ExecuteNonQuery();
                connection.Close();
                MessageBox.Show("注册成功!");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            this.Close();
        }

密码加密

public static string EncryptWithMD5(string source)//MD5加密
        {
            byte[] sor = Encoding.UTF8.GetBytes(source);
            MD5 md5 = MD5.Create();
            byte[] result = md5.ComputeHash(sor);
            StringBuilder strbul = new StringBuilder(40);
            for (int i = 0; i < result.Length; i++)
            {
                strbul.Append(result[i].ToString("x2"));//加密结果"x2"结果为32位,"x3"结果为48位,"x4"结果为64位
            }
            return strbul.ToString();
        }

对密码、学号和联系方式的限制

private void textBoxPassword_Leave(object sender, EventArgs e)//对密码的设置
        {
            if (textBoxPassword.Text.Trim() != "")
            {
                //使用regex(正则表达式)进行格式设置 至少有数字、大写字母各一个。最少3个字符、最长20个字符。
                Regex regex = new Regex(@"(?=.*[0-9])(?=.*[A-Z]).{3,20}");

                if (regex.IsMatch(textBoxPassword.Text))//判断格式是否符合要求
                {
                    //MessageBox.Show("输入密码格式正确!");
                }
                else
                {
                    MessageBox.Show("密码由至少一个大写字母、最少3个字符组成!");
                    textBoxPassword.Focus();
                }
            }
            else
            {
                MessageBox.Show("密码不能为空!");
            }

        }

        private void textBoxNum_Leave(object sender, EventArgs e)//对学号/工号的设置
        {
            if (textBoxNum.Text.Trim() != "")
            {
                //使用regex(正则表达式)进行格式设置 至少有数字最少7个字符、最长20个字符。
                Regex regex = new Regex(@"(?=.*[0-9]).{7,20}");

                if (regex.IsMatch(textBoxNum.Text))//判断格式是否符合要求
                {
                    //MessageBox.Show("输入密码格式正确!");
                }
                else
                {
                    MessageBox.Show("学号/工号至少为7个字符、最长20个字符!");
                    textBoxNum.Focus();
                }
            }
            else
            {
                MessageBox.Show("用户名不能为空!");
            }

        }

        private void textBoxNumber_Leave(object sender, EventArgs e)//联系方式设置
        {
            if (textBoxNumber.Text.Trim() != "")
            {
                //使用regex(正则表达式)进行格式设置 至少有数字最少7个字符、最长20个字符。
                Regex regex = new Regex(@"(?=.*[0-9]).{7,20}");

                if (regex.IsMatch(textBoxNumber.Text))//判断格式是否符合要求
                {
                    //MessageBox.Show("输入联系方式格式正确!");
                }
                else
                {
                    MessageBox.Show("联系方式至少有7个字符、最长20个字符!");
                    textBoxNumber.Focus();
                }
            }
            else
            {
                //MessageBox.Show("联系方式不能为空!");
            }
        }

上传照片

private void buttonphoto_Click(object sender, EventArgs e)//上传照片
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.ShowDialog();
            string picturePath = openFileDialog.FileName;//获取图片路径
            //创建FileStream对象
            FileStream fs = new FileStream(picturePath, FileMode.Open, FileAccess.Read);
            //声明Byte数组
            mybyte = new byte[fs.Length];
            //读取数据
            fs.Read(mybyte, 0, mybyte.Length);
            Image image = Image.FromStream(fs);
            userphoto.Image = image;
            fs.Close();
        }
  • 学生登陆
    C#学生信息管理系统-代码展示_第3张图片
    个人信息
public FormStudent()
        {
            InitializeComponent();
           
            Form1 form1 = new Form1();   //将登陆窗体的账号传递到此窗体
            label7.Text = form1.Get();
            
            
            //取出图片
            SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=Text;User ID=sa;Password=110023");
            conn.Open();
            String select_by_id = "select UserPhoto from UserMessage where UserID='" + label7.Text + "'";
            SqlCommand sqlCommand1 = new SqlCommand(select_by_id, conn);
          
            DataSet dt = new DataSet();
            SqlDataAdapter da = new SqlDataAdapter(select_by_id, conn);
            da.Fill(dt,"UserMessage");

            int c = dt.Tables["UserMessage"].Rows.Count;
            if (c > 0)
            {
                Byte[] mybyte = new byte[0];
                mybyte = (Byte[])(dt.Tables["UserMessage"].Rows[c - 1]["UserPhoto"]);
                MemoryStream ms = new MemoryStream(mybyte);
                pictureBox1.Image = Image.FromStream(ms);
            }
            else
                pictureBox1.Image = null;
            conn.Close();


        }

        private void 个人信息ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            panel3.Show();

            string StuSno = label7.Text.Trim();
            String conn = "Data Source =.; Initial Catalog = Text;  Persist Security Info = True;User ID = sa; Password = 110023";
            SqlConnection sqlconnection = new SqlConnection(conn);//实例化连接对象


            try
            {
                sqlconnection.Open();
                String select_by_sno = "select * from Student where Sno='" + StuSno + "'";//数据库操作的代码
                SqlCommand cmd = new SqlCommand(select_by_sno, sqlconnection);
                SqlDataReader sqlDataReader = cmd.ExecuteReader();//返回读取到的数据
                BindingSource bindingsource = new BindingSource();//封装窗体的数据源
                bindingsource.DataSource = sqlDataReader; ;//将读到的数据传递给窗体的数据源

                dataGridView1.DataSource = bindingsource;//再将数据源赋值给dataGridView
            }
            catch
            {
                MessageBox.Show("查询语句有误,请认真检查SQL语句");
            }
            finally
            {
                sqlconnection.Close();//关闭数据库连接
            }



        }

选课管理

private void 选课结果ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            panel1.Show();
           panel2.Hide();
            panel3.Hide();

            string StuSno = label7.Text.Trim();
            String conn = "Data Source =.; Initial Catalog = Text;  Persist Security Info = True;User ID = sa; Password = 110023";
            SqlConnection sqlconnection = new SqlConnection(conn);//实例化连接对象


            try
            {
                sqlconnection.Open();
                String select_by_sno = "select * from SC where Sno='" + StuSno + "'";//数据库操作的代码
                SqlCommand cmd = new SqlCommand(select_by_sno, sqlconnection);
                SqlDataReader sqlDataReader = cmd.ExecuteReader();//返回读取到的数据
                BindingSource bindingsource = new BindingSource();//封装窗体的数据源
                bindingsource.DataSource = sqlDataReader; ;//将读到的数据传递给窗体的数据源

                dataGridView2.DataSource = bindingsource;//再将数据源赋值给dataGridView
            }
            catch
            {
                MessageBox.Show("查询语句有误,请认真检查SQL语句");
            }
            finally
            {
                sqlconnection.Close();//关闭数据库连接
            }
        }

成绩查询

private void 成绩查询ToolStripMenuItem_Click(object sender, EventArgs e)
        {
           //panel1.Hide();
           //panel2.Hide();
            panel2.Show();
           
        }

        private void button1_Click(object sender, EventArgs e)  //查询
        {
            string StuSno = label7.Text.Trim();
            string StuCno = textBox1.Text.Trim();
            String conn = "Data Source =.; Initial Catalog = Text;  Persist Security Info = True;User ID = sa; Password = 110023";
            SqlConnection sqlconnection = new SqlConnection(conn);//实例化连接对象
            try
            { 
                sqlconnection.Open();
                String select_by_sno = "select * from SC where Sno='" + StuSno + "'and Cno ='" +StuCno+"'";//数据库操作的代码
                SqlCommand cmd = new SqlCommand(select_by_sno, sqlconnection);
                SqlDataReader sqlDataReader = cmd.ExecuteReader();//返回读取到的数据
                BindingSource bindingsource = new BindingSource();//封装窗体的数据源
                bindingsource.DataSource = sqlDataReader; ;//将读到的数据传递给窗体的数据源

                dataGridView3.DataSource = bindingsource;//再将数据源赋值给dataGridView
            }
            catch
            {
                MessageBox.Show("查询语句有误,请认真检查SQL语句");
            }
            finally
            {
                sqlconnection.Close();//关闭数据库连接
            }
        }
  • 管理员登陆
    C#学生信息管理系统-代码展示_第4张图片
private void button1_Click_1(object sender, EventArgs e)//管理信息
        {
            StuInfor stuinfor = new StuInfor();
            stuinfor.Show();
        }

        private void button2_Click(object sender, EventArgs e)//管理成绩
        {
            StuGrade stuGrade = new StuGrade();
            stuGrade.Show();
        }

        private void button3_Click(object sender, EventArgs e)//管理课程
        {
            StuCourse stuCourse = new StuCourse();
            stuCourse.Show();
        }

学生信息管理
C#学生信息管理系统-代码展示_第5张图片
增加

SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=Text;Persist Security Info=True;User ID=sa;Password=110023");

        private void buttonAdd_Click(object sender, EventArgs e)//增加
        {
            string StuSno = textBoxsno.Text.Trim();
            string StuSname = textBoxsname.Text.Trim();
            string StuSsex = textBoxsex.Text.Trim();
            string StuSage = textBoxsage.Text.Trim();
            string StuSdept = textBoxsdept.Text.Trim();
            //SqlConnection con = new SqlConnection("Data Source =.; Initial Catalog = Text;  Persist Security Info = True;User ID = sa; Password = 110023"); //连接数据库
            try
            {
                con.Open();     //打开数据库
                string insertStr = "INSERT INTO Student(Sno,Sname,Ssex,Sage,Sdept)" + "VALUES('" + StuSno + "','" + StuSname + "','" + StuSsex + "'," + StuSage + ",'" + StuSdept + "')";
                SqlCommand cmd = new SqlCommand(insertStr, con);
                cmd.ExecuteNonQuery();      //将增加后的信息直接显示出来

            }
            catch
            {
                MessageBox.Show("输入数据违法要求!");
                
            }
            finally
            {
                con.Close();      //关闭数据库
            }
            this.studentTableAdapter.Fill(this.textDataSet1.Student);
        }

删除

private void buttonDelete_Click(object sender, EventArgs e)//删除
        {
            try
            {
                con.Open();     //打开数据库
                string select_Sno = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();//选择的当前行第一列的值,也就是Sno
                string delete_by_Sno = "DELETE FROM Student WHERE Sno='" + select_Sno + "'";//sql删除语句
                SqlCommand cmd = new SqlCommand(delete_by_Sno, con);
                cmd.ExecuteNonQuery();      //将增加后的信息直接出来
            }
            catch
            {
                MessageBox.Show("请选择正确行!");
            }
            finally
            {
                con.Close();      //关闭数据库
            }
            this.studentTableAdapter.Fill(this.textDataSet1.Student);

        }

在数据库中增加性别限制

ALTER TABLE Student ADD CONSTRAINT C1 CHECK(Ssex IN('男','女')); 

删除

 private void buttonDelete_Click(object sender, EventArgs e)//删除
        {
            try
            {
                con.Open();     //打开数据库
                string select_Sno = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();//选择的当前行第一列的值,也就是Sno
                string delete_by_Sno = "DELETE FROM Student WHERE Sno='" + select_Sno + "'";//sql删除语句
                SqlCommand cmd = new SqlCommand(delete_by_Sno, con);
                cmd.ExecuteNonQuery();      //将增加后的信息直接出来
            }
            catch
            {
                MessageBox.Show("请选择正确行!");
            }
            finally
            {
                con.Close();      //关闭数据库
            }
            this.studentTableAdapter.Fill(this.textDataSet1.Student);

        }

修改

private void buttonModify_Click(object sender, EventArgs e)//修改
        {
            string StuSno = textBoxsno.Text.Trim();
            string StuSname = textBoxsname.Text.Trim();
            string StuSsex = textBoxsex.Text.Trim();
            string StuSage = textBoxsage.Text.Trim();
            string StuSdept = textBoxsdept.Text.Trim();
            try
            {
                string insertStr = "";
                string insertStr1 = "";
                string insertStr2 = "";
                string insertStr3 = "";
                con.Open();
                if (StuSname != "")
                {
                    insertStr = "UPDATE Student SET Sname = '" + StuSname + "' WHERE Sno = '" + StuSno + "'";    //修改名字
                    SqlCommand cmd = new SqlCommand(insertStr, con);
                    cmd.ExecuteNonQuery();
                }

                if (StuSsex != "")
                {
                    insertStr1 = "UPDATE Student SET Ssex = '" + StuSsex + "' WHERE Sno = '" + StuSno + "'";    //修改性别
                    SqlCommand cmd1 = new SqlCommand(insertStr1, con);
                    cmd1.ExecuteNonQuery();
                }
                if (StuSdept != "")
                {
                    insertStr2 = "UPDATE Student SET Sdept = '" + StuSdept + "' WHERE Sno = '" + StuSno + "'";    //修改专业
                    SqlCommand cmd2 = new SqlCommand(insertStr2, con);
                    cmd2.ExecuteNonQuery();
                }
                if (StuSage != "")
                {
                    insertStr3 = "UPDATE Student SET Sage = '" + StuSage + "' WHERE Sno = '" + StuSno + "'";    //修改年龄
                    SqlCommand cmd3 = new SqlCommand(insertStr3, con);
                    cmd3.ExecuteNonQuery();
                }
            }
            catch
            {
                MessageBox.Show("输入数据违反要求");
            }
            finally
            {
                con.Close();      //关闭数据库
            }
            this.studentTableAdapter.Fill(this.textDataSet1.Student);
        }

查询

private void buttonSearch_Click(object sender, EventArgs e)//查询
        {
            string StuSno = textBoxsno.Text.Trim();
            string StuSname = textBoxsname.Text.Trim();
            string StuSsex = textBoxsex.Text.Trim();
            string StuSage = textBoxsage.Text.Trim();
            string StuSdept = textBoxsdept.Text.Trim();
            String conn = "Data Source =.; Initial Catalog = Text;  Persist Security Info = True;User ID = sa; Password = 110023";
            SqlConnection sqlconnection = new SqlConnection(conn);//实例化连接对象
            try
            {
                String select_by_id = "select * from Student where ";
                int flag = 0;
                sqlconnection.Open();
                if (StuSno != "")
                    select_by_id += "Sno='" + StuSno + "'";    // 按学号查
                if (StuSname != "")
                {
                    if (flag == 0)
                    {
                        select_by_id += "Sname LIKE'" + StuSname + "'";
                        flag = 1;
                    }
                    if (flag == 1)
                        select_by_id += "And Sname LIKE'" + StuSname + "'";
                }
                if (StuSage != "")
                {
                    if (flag == 0)
                    {
                        select_by_id += "Sage='" + StuSage + "'";
                        flag = 1;
                    }
                    if (flag == 1)
                        select_by_id += "And Sage='" + StuSage + "'";
                }
                if (StuSdept != "")
                {
                    if (flag == 0)
                    {
                        select_by_id += "Sdept='" + StuSdept + "'";
                        flag = 1;
                    }
                    if (flag == 1)
                        select_by_id += "And Sdept='" + StuSdept + "'";
                }
                if (StuSsex != "")
                {
                    if (flag == 0)
                    {
                        select_by_id += "Ssex='" + StuSsex + "'";
                        flag = 1;
                    }
                    if (flag == 1)
                        select_by_id += "And Ssex='" + StuSsex + "'";
                }
                
                    SqlCommand sqlcommand = new SqlCommand(select_by_id, sqlconnection);
                    SqlDataReader sqldatareader = sqlcommand.ExecuteReader();
                    BindingSource bindingsource = new BindingSource();
                    bindingsource.DataSource = sqldatareader;
                     dataGridView1.DataSource = bindingsource;
                   
                }
            catch
            {
                MessageBox.Show("查询语句有误,请认真检查SQL语句");
            }
            finally
            {
                sqlconnection.Close();
            }
        }

学生成绩管理
C#学生信息管理系统-代码展示_第6张图片
增加

private void buttonAdd_Click(object sender, EventArgs e)//增加
        {
            string StuSno = textBoxsno.Text.Trim();
            string StuCno = textBoxcno.Text.Trim();
            string StuGrade = textBoxgrade.Text.Trim();
            try
            {
                con.Open();     //打开数据库
                string insertStr = "INSERT INTO SC(Sno,Cno,Grade)" + "VALUES('" + StuSno + "','" + StuCno + "','" + StuGrade + "')";
                SqlCommand cmd = new SqlCommand(insertStr, con);
                cmd.ExecuteNonQuery();      //将增加后的信息直接显示出来
            }
            catch
            {
                MessageBox.Show("输入数据违法要求!");
            }
            finally
            {
                con.Close();
            }
            this.sCTableAdapter.Fill(this.textDataSet2.SC);
        }

删除

private void buttonDelete_Click(object sender, EventArgs e)//删除
        {
            try
            {
                con.Open();    //打开
                string select_id = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();//选择的当前行第一列的值,也就是ID
                string select_cno = dataGridView1.SelectedRows[0].Cells[1].Value.ToString();//选择的当前行第2列的值,也就是cno
                string delete_by_id = "delete from SC where Sno=" + select_id + "AND Cno=" + select_cno;//sql删除语句
                SqlCommand cmd = new SqlCommand(delete_by_id, con);    
                cmd.ExecuteNonQuery(); 
            }
            catch
            {
                MessageBox.Show("请选择正确行!");
            }
            finally
            {
                con.Close();      //关闭数据库
            }
            this.sCTableAdapter.Fill(this.textDataSet2.SC);
        }

修改

private void buttonModify_Click(object sender, EventArgs e)//修改分数
        {
            string StuSno = textBoxsno.Text.Trim();
            string StuCno = textBoxcno.Text.Trim();
            string StuGrade = textBoxgrade.Text.Trim();
            try
            {
                string insertStr = "";
                string insertStr1 = "";
                con.Open();
                if (StuCno != "")
                {
                    insertStr = "UPDATE SC SET Cno = '" + StuCno + "' WHERE Sno = '" + StuSno + "'" + "AND Grade='" + StuGrade + "'";    //修改课程
                    SqlCommand cmd = new SqlCommand(insertStr, con);
                    cmd.ExecuteNonQuery();
                }
                if (StuGrade != "")
                {
                    insertStr1 = "UPDATE SC SET Grade = '" + StuGrade + "' WHERE Sno = '" + StuSno + "'" + "AND Cno='" + StuCno + "'"; ;    //修改成绩
                    SqlCommand cmd1 = new SqlCommand(insertStr1, con);
                    cmd1.ExecuteNonQuery();
                }
            }
            catch
            {
                MessageBox.Show("输入数据违反要求");
            }
            finally
            {
                con.Close();      //关闭数据库
            }
            this.sCTableAdapter.Fill(this.textDataSet2.SC);
        }

查询

SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=Text;Persist Security Info=True;User ID=sa;Password=110023");
        private void buttonSearch_Click(object sender, EventArgs e)//查询
        {
            string StuSno = textBoxsno.Text.Trim();
            string StuCno = textBoxcno.Text.Trim();
            string StuGrade = textBoxgrade.Text.Trim();
            String conn = "Data Source =.; Initial Catalog = Text;  Persist Security Info = True;User ID = sa; Password = 110023";
            SqlConnection sqlconnection = new SqlConnection(conn);//实例化连接对象
            try
            {
                String select_by_id = "select * from SC where ";
                int flag = 0;  
                sqlconnection.Open();
                if (StuSno != "")
                {
                    select_by_id += "Sno='" + StuSno + "'"; flag = 1;  //按学号查询
                } 
                if (StuCno != "")
                {
                    if (flag == 0)
                    {
                        select_by_id += "Cno='" + StuCno + "'" + " ORDER BY Grade DESC";//按课程号查询
                        flag = 1;
                    }
                    else if (flag == 1)
                    { select_by_id += "And Cno='" + StuCno + "'"; } //按学号和课程号查询

                }
                SqlCommand sqlCommand = new SqlCommand(select_by_id, sqlconnection);
                SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();
                BindingSource bindingSource = new BindingSource();
                bindingSource.DataSource = sqlDataReader;
                dataGridView1.DataSource = bindingSource;

            }
            catch
            {
                MessageBox.Show("查询语句有误,请认真检查SQL语句!");
            }
            finally
            {
                sqlconnection.Close();
            }
        }

学生课程管理
C#学生信息管理系统-代码展示_第7张图片
增加

SqlConnection con = new SqlConnection("Data Source =.; Initial Catalog = Text;  Persist Security Info = True;User ID = sa; Password = 110023"); //连接数据库
        private void buttonAdd_Click(object sender, EventArgs e)//增加
        {
            String StuCno = textBoxcno.Text.Trim();
            String StuCname = textBoxcname.Text.Trim();
            String StuCpno = textBoxcpno.Text.Trim();
            String StuCcredit = textBoxccredit.Text.Trim();                 //读取需要插入的值
            //SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=STUDENT;Persist Security Info=True;User ID=sa;Password=tangdou");
            try
            {
                con.Open();
                string insertStr = "INSERT INTO  Course (Cno,Cname,Cpno,Ccredit)    " +              //拼接字符串
                    "VALUES ('" + StuCno + "','" + StuCname + "','" + StuCpno + "','" + StuCcredit + "')";
                SqlCommand cmd = new SqlCommand(insertStr, con);
                cmd.ExecuteNonQuery();
            }
            catch
            {
                MessageBox.Show("输入数据违反要求!");
            }
            finally
            {
                con.Close();
            }
            this.courseTableAdapter.Fill(this.textDataSet3.Course);

        }

删除

private void buttonDelete_Click(object sender, EventArgs e)//删除
        {
            try
            {
                con.Open();     //打开数据库
                string select_Cno = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();//选择的当前行第一列的值,也就是Sno
                string delete_by_Cno = "DELETE FROM Course WHERE Cno='" + select_Cno + "'";//sql删除语句
                SqlCommand cmd = new SqlCommand(delete_by_Cno, con);
                cmd.ExecuteNonQuery();      //将增加后的信息直接出来
            }
            catch
            {
                MessageBox.Show("请选择正确行!");
            }
            finally
            {
                con.Close();      //关闭数据库
            }
            this.courseTableAdapter.Fill(this.textDataSet3.Course);
        }

修改

private void buttonModify_Click(object sender, EventArgs e)//修改
        {
            string StuCno = textBoxcno.Text.Trim();
            string StuCname = textBoxcname.Text.Trim();
            string StuCpno = textBoxcpno.Text.Trim();
            string StuCcredit = textBoxccredit.Text.Trim();

            try
            {
                string insertStr = "";
                string insertStr1 = "";
                string insertStr2 = "";
               

                con.Open();
                if (StuCname != "")
                {
                    insertStr = "UPDATE Course SET Cname = '" + StuCname + "' WHERE Cno = '" + StuCno + "'";    //修改名字
                    SqlCommand cmd = new SqlCommand(insertStr, con);
                    cmd.ExecuteNonQuery();
                }

                if (StuCpno != "")
                {
                    insertStr1 = "UPDATE Course SET Cpno = '" + StuCpno + "' WHERE Cno = '" + StuCno + "'";    //修改先行课
                    SqlCommand cmd = new SqlCommand(insertStr1, con);
                    cmd.ExecuteNonQuery();
                }
                if (StuCcredit != "")
                {
                    insertStr2 = "UPDATE Course SET Ccredit = '" + StuCcredit + "' WHERE Cno = '" + StuCno + "'";    //修改学分
                    SqlCommand cmd2 = new SqlCommand(insertStr2, con);
                    cmd2.ExecuteNonQuery();
                }
            }
            catch
            {
                MessageBox.Show("输入数据违反要求");
            }
            finally
            {
                con.Close();      //关闭数据库
            }
            this.courseTableAdapter.Fill(this.textDataSet3.Course);
        }

查询

private void buttonSearch_Click(object sender, EventArgs e)//查询
        {
            string StuCno = textBoxcno.Text.Trim();
            string StuCname = textBoxcname.Text.Trim();

            String conn = "Data Source =.; Initial Catalog = Text;  Persist Security Info = True;User ID = sa; Password = 110023";
            SqlConnection sqlconnection = new SqlConnection(conn);//实例化连接对象
            try
            {
                sqlconnection.Open();
                if (StuCno != "") //按课程号查
                {
                    String select_by_cno = "select * from Course where Cno='" + StuCno + "'";
                    SqlCommand sqlcommand = new SqlCommand(select_by_cno, sqlconnection);
                    SqlDataReader sqldatareader = sqlcommand.ExecuteReader();
                    BindingSource bindingsource = new BindingSource();
                    bindingsource.DataSource = sqldatareader;
                    dataGridView1.DataSource = bindingsource;
                }
                if (StuCname != "") //按课程名查
                {
                    String select_by_cname = "select * from Course where Cname='" + StuCname + "'";
                    SqlCommand sqlcommand = new SqlCommand(select_by_cname, sqlconnection);
                    SqlDataReader sqldatareader = sqlcommand.ExecuteReader();
                    BindingSource bindingsource = new BindingSource();
                    bindingsource.DataSource = sqldatareader;
                    dataGridView1.DataSource = bindingsource;
                }
            }
            catch
            {
                MessageBox.Show("查询语句有误,请认真检查SQL语句");
            }
            finally
            {
                sqlconnection.Close();
            }
        
        }
  • 数据库中的代码
DROP TABLE IF EXISTS SC
DROP TABLE IF EXISTS Student
DROP TABLE IF EXISTS Course
DROP TABLE IF EXISTS UserMessage


CREATE TABLE UserMessage        
 (	
 UserID NCHAR(20) PRIMARY KEY,                          
 UserPassWord NCHAR(32) ,            
 UserMobile NCHAR(11),
 UserBirthday datetime,
 UserIdentity NCHAR(20),
 UserPhoto image
 ); 


 CREATE TABLE SysLog          
 (	
 UserID NCHAR(20) ,                          
 DateAndTime datetime,
 UserOperation NCHAR(200)
 ); 

CREATE TABLE Student          
 (	
 Sno CHAR(9) PRIMARY KEY,        /* 列级完整性约束条件,Sno是主码*/                  
 Sname CHAR(20) UNIQUE,             /* Sname取唯一值*/
 Ssex CHAR(2),
 Sage SMALLINT,
 Sdept CHAR(20)
 ); 

CREATE TABLE  Course
 (	
 Cno CHAR(4) PRIMARY KEY,
 Cname CHAR(40),            
 Cpno CHAR(4),               	                      
 Ccredit SMALLINT,
 FOREIGN KEY (Cpno) REFERENCES  Course(Cno) 
 ); 

CREATE TABLE  SC
 (
 Sno CHAR(9), 
 Cno CHAR(4),  
 Grade SMALLINT,
 PRIMARY KEY (Sno,Cno),                     /* 主码由两个属性构成,必须作为表级完整性进行定义*/
 FOREIGN KEY (Sno) REFERENCES Student(Sno),  /* 表级完整性约束条件,Sno是外码,被参照表是Student */
 FOREIGN KEY (Cno)REFERENCES Course(Cno)     /* 表级完整性约束条件, Cno是外码,被参照表是Course*/
 ); 


INSERT  INTO  Student (Sno,Sname,Ssex,Sdept,Sage) VALUES ('201215121','李勇','男','CS',20);
INSERT  INTO  Student (Sno,Sname,Ssex,Sdept,Sage) VALUES ('201215122','刘晨','女','CS',19);
INSERT  INTO  Student (Sno,Sname,Ssex,Sdept,Sage) VALUES ('201215123','王敏','女','MA',18);
INSERT  INTO  Student (Sno,Sname,Ssex,Sdept,Sage) VALUES ('201215125','张立','男','IS',19);
INSERT  INTO  Student (Sno,Sname,Ssex,Sdept,Sage) VALUES ('201215128','陈冬','男','IS',20);

SELECT * FROM Student

INSERT  INTO Course(Cno,Cname,Cpno,Ccredit)	VALUES ('1','数据库',NULL,4);
INSERT  INTO Course(Cno,Cname,Cpno,Ccredit)	VALUES ('2','数学',NULL,4);
INSERT  INTO Course(Cno,Cname,Cpno,Ccredit)	VALUES ('3','信息系统',NULL,4);
INSERT  INTO Course(Cno,Cname,Cpno,Ccredit)	VALUES ('4','操作系统',NULL,4);
INSERT  INTO Course(Cno,Cname,Cpno,Ccredit)	VALUES ('5','数据结构',NULL,4);
INSERT  INTO Course(Cno,Cname,Cpno,Ccredit)	VALUES ('6','数据处理',NULL,4);
INSERT  INTO Course(Cno,Cname,Cpno,Ccredit)	VALUES ('7','Pascal语言',NULL,4);

UPDATE Course SET Cpno = '5' WHERE Cno = '1' 
UPDATE Course SET Cpno = '1' WHERE Cno = '3' 
UPDATE Course SET Cpno = '6' WHERE Cno = '4' 
UPDATE Course SET Cpno = '7' WHERE Cno = '5' 
UPDATE Course SET Cpno = '6' WHERE Cno = '7' 

SELECT * FROM Course

INSERT  INTO SC(Sno,Cno,Grade) VALUES ('201215121 ','1',92);
INSERT  INTO SC(Sno,Cno,Grade) VALUES ('201215121 ','2',85);
INSERT  INTO SC(Sno,Cno,Grade) VALUES ('201215121 ','3',88);
INSERT  INTO SC(Sno,Cno,Grade) VALUES ('201215122 ','2',90);
INSERT  INTO SC(Sno,Cno,Grade) VALUES ('201215122 ','3',80);

SELECT * FROM SC


//新建触发器
IF(OBJECT_ID('regist_recorder') is not null)        -- 判断名为 regist_recorder 的触发器是否存在
DROP TRIGGER regist_recorder      
GO

CREATE TRIGGER regist_recorder
ON UserMessage 	         
AFTER
INSERT
AS 
	declare @UserName    nchar(20)
	declare @DateTime    datetime
	declare @UserOperation nchar(200)

	select @UserName = system_user
	select @DateTime = CONVERT(datetime,GETDATE(),120) 
	declare @op varchar(10)
	select @op=case when exists(select 1 from inserted) and exists(select 1 from deleted)
                   then 'Update'
                   when exists(select 1 from inserted) and not exists(select 1 from deleted)
                   then 'Insert'
                   when not exists(select 1 from inserted) and exists(select 1 from deleted)
                   then 'Delete' end
                   
	select @UserOperation = @op
	INSERT INTO SysLog(UserID,DateAndTime,UserOperation)
	VALUES (@UserName,@DateTime,@UserOperation)


视频讲解:C#学生信息管理系统

你可能感兴趣的:(C#学生信息管理系统-代码展示)