[C#: Sistema de gestión de la información de los estudiantes-Código de pieza 1]

Cree el proyecto Aplicación de Windows Forms:

Cree una clase DBhelp.cs, conéctese a la base de datos, simplemente llame a esta clase cada vez: llame a esto: DBhelp.conn.Open();

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;

namespace Win9_28
{
    public static class DBhelp
    {
        static string  strconn = "Data Source=.;Initial Catalog=studentInf;Integrated Security=True";
        public static SqlConnection conn = new SqlConnection(strconn);
        public static SqlCommand comm = new SqlCommand();
        //public static SqlDataReader read = comm.ExecuteReader();
    }
}

1. Haga clic en el elemento para agregar el elemento: Windows Form, escriba el formulario de inicio de sesión: Login.cs:

Primero: modifique la propiedad Prueba del formulario para iniciar sesión y la propiedad (Nombre) para frmLogin

Agregue un control de imagen Control PictureBox, (Nombre) llamado: pictureBox1, propiedad de imagen: importar imagen, propiedad SizeMode: StretchImage para mostrar la imagen completa

Agregue un control de Etiqueta (Nombre) llamado: lblUserName, Texto: nombre de usuario, control de cuadro de entrada TextBox, (Nombre): txtUserName

Agregue un control de etiqueta (Nombre) llamado: lblUserPwd, Texto: contraseña, control de cuadro de entrada TextBox, (Nombre): txtUserPwd, si desea que no se muestre la contraseña, establezca la propiedad PasswordChar: *

Agregue 2 controles de botón, el primero (Nombre): btnRegister Texto: Iniciar sesión, el último (Nombre): btnESC Texto: Cancelar

El estilo es el siguiente:

El método en el botón de inicio de sesión: haga doble clic en el botón de inicio de sesión: se generará automáticamente un evento de botón de inicio de sesión en segundo plano qu

private void btnRegister_Click(object sender, EventArgs e)
        {
            string strconn = "Data Source=.;Initial Catalog=studentInf;Integrated Security=True";
            SqlConnection conn = new SqlConnection(strconn);//创建SqlConnection对象,连接数据库
            string name = txtUserName.Text;//获取姓名文本框的内容
            string pwd = txtUserPwd.Text;//获取密码文本框的内容
            try
            {
                conn.Open();
                string sqlstr=string.Format("select * from tb_User where UserName='{0}' and UserPasswd='{1}'",name,pwd);
                SqlCommand comm = new SqlCommand();//创建sqlCommand对象,执行SQL语句
                comm.Connection = conn;//执行SqlCommand对象的Connection属性,设置Command对象的Connection对象
                comm.CommandText = sqlstr;//执行SqlCommand对象的的CommandText属性,设置Command对象的sql语句

                /*
                if (name == string.Empty || pwd == string.Empty)
                {
                    MessageBox.Show("用户名或密码不能为空", "系统提示");
                }*/


                if (comm.ExecuteScalar() == null)//ExecuteScalar()返回查询结果集中的第一行第一列,没有返回null
                {
                    MessageBox.Show("用户名与密码不匹配,登录失败");//提示信息
                    this.txtUserName.Clear();
                    this.txtUserPwd.Clear();
                    this.txtUserName.Focus();

                }
                else 
                {
                    //this.Hide();//此页面隐藏
                    frmMain frmmain = new frmMain();//创建新的页面
                    frmmain.Show();//打开新的页面
                }
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }
            finally
            {
             conn.Close();
            }
        }

El método de cancelar el botón, haga doble clic en el botón cancelar:

private void btnESC_Click(object sender, EventArgs e)
        {
            Application.Exit();//退出程序,结束运行
        }

2. Agregue la página de la universidad: frmAddCollege.cs

 Cambie la propiedad Texto del formulario: agregue información del departamento, (Nombre): propiedad: frmAddCollege

Agregue dos controles Lable, agregue dos controles de cuadro de entrada de texto TextBox, llamados: txtDepartmentID, txtDepartmentName, agregue dos controles de botón Botón y comando para ellos, cambie el valor de Texto requerido

Haga doble clic en el botón Agregar para agregar un evento OnClick para el botón Agregar. El código es el siguiente:

private void btnAdd_Click(object sender, EventArgs e)
        {
            string conn = "Data Source=.;Initial Catalog=studentInf;Integrated Security=True";
            SqlConnection a = new SqlConnection(conn);//创建Connection对象

            if (txtDepartmentID.Text == "" || txtDepartmentName.Text == "")
            {
                MessageBox.Show("院系编号或院系名称不能为空!");
            }
            else
            {
                try
                {
                    a.Open();
                    string sqlstr = string.Format("insert into tb_College values('{0}','{1}')", txtDepartmentID.Text, txtDepartmentName.Text);

                    SqlCommand comm = new SqlCommand();//创建Command 对象执行SQL语句
                    comm.Connection = a;
                    comm.CommandText = sqlstr;
                    //int result = comm.ExecuteNonQuery();

                    if (comm.ExecuteNonQuery() > 0)
                    {
                        MessageBox.Show("插入成功");
                    }
                    else
                    {
                        MessageBox.Show("插入失败");
                    }
                }
                catch (Exception ex)
                {

                    MessageBox.Show(ex.Message);
                }
                finally
                {
                    a.Close();
                }
            }
        }

Agregue un evento de clic para que el botón cancelar cierre esta página:

private void btnClose_Click(object sender, EventArgs e)
        {
            this.Hide();
        }

2. Crear formulario frmEditCollege.cs

 

 Modifique el formulario (Nombre) como: frmEditCollege, Texto: Sistema de información de la facultad

Agregue un control de datos: control dataGridView, haga clic en el pequeño triángulo de arriba, agregue la fuente de datos - seleccione la fuente de datos - agregue la fuente de datos - base de datos - conjunto de datos - tabla dentro, agregue la fuente de datos

Al agregar dos controles de etiqueta, el texto se llama: Número de departamento:, Nombre del departamento, agregue dos cuadros de texto y agregue 4 botones

Cuando desee que los datos de la fuente de datos de la tienda se muestren en el cuadro de texto inferior, agregue dos veces el control de datos y agregue el siguiente código: 

​​ private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            txtCollegeNo.Text = this.dataGridView1.CurrentRow.Cells[0].Value.ToString();
            txtCollegeName.Text = this.dataGridView1.CurrentRow.Cells[1].Value.ToString();
        }

Para el botón de consulta, agregue un evento de clic, el código es el siguiente:

private void btnSelect_Click(object sender, EventArgs e)
        {
            string conn = "Data Source=.;Initial Catalog=studentInf;Integrated Security=True";
            SqlConnection a = new SqlConnection(conn);

            try
            {
                a.Open();
                string sqlstr = string.Format("select * from tb_College where DepartmentID='{0}'", txtCollegeNo.Text);//Format转化为字符串
                SqlCommand comm = new SqlCommand();
                comm.Connection = a;
                comm.CommandText = sqlstr;

                SqlDataReader read = comm.ExecuteReader();//创建DataReader对象,在数据库中读取数据
                if (read.Read())
                {
                    txtCollegeName.Text = read[1].ToString();
                }
                else
                {
                    MessageBox.Show("查询结果不存在!");
                    txtCollegeName.Text = "";
                }


            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }
            finally
            {
                a.Close();
            }
        }

Haga doble clic en el botón Eliminar para agregar un evento de clic:

private void btnDelete_Click(object sender, EventArgs e)
        {
            try
            {
                DBhelp.conn.Open();
                string sqlstr = string.Format("delete from tb_College where DepartmentID='{0}'and DepartmentName='{1}' ", txtCollegeNo.Text, txtCollegeName.Text);
                DBhelp.comm.CommandText = sqlstr;
                DBhelp.comm.Connection = DBhelp.conn;

                if ((int)DBhelp.comm.ExecuteNonQuery() > 0)
                {
                    MessageBox.Show("删除成功");

                }
                else
                {
                    MessageBox.Show("删除失败");
                }
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }
            finally
            {
                DBhelp.conn.Close();
            }
        }

Haga doble clic en el botón Modificar para agregar un evento de clic:

 private void btnCollege_Click(object sender, EventArgs e)
        {
            /*string conn = "Data Source=.;Initial Catalog=studentInf;Integrated Security=True";
            SqlConnection a = new SqlConnection(conn);

            if (txtCollegeNo.Text == "" || txtCollegeName.Text == "")
            {
                MessageBox.Show("院系编号或院系名称不能为空!");
            }
            else
            {
                try
                {
                    a.Open();
                    string sqlstr = string.Format("insert into tb_College values('{0}','{1}')", txtCollegeNo.Text, txtCollegeName.Text);

                    SqlCommand comm = new SqlCommand();
                    comm.Connection = a;
                    comm.CommandText = sqlstr;
                    int result = comm.ExecuteNonQuery();

                    if (result != 0)
                    {
                        MessageBox.Show("插入成功");
                    }
                    else
                    {
                        MessageBox.Show("插入失败");
                    }
                }
                catch (Exception ex)
                {

                    MessageBox.Show(ex.Message);
                }
                finally
                {
                    a.Close();
                }
            }*/
            //上面代码无用
            try
            {
                DBhelp.conn.Open();
                string sqlstr = string.Format("update tb_College set DepartmentName='{0}' where DepartmentID='{1}'",txtCollegeName.Text,txtCollegeNo.Text);
                DBhelp.comm.CommandText = sqlstr;
                DBhelp.comm.Connection = DBhelp.conn;

                if ((int)DBhelp.comm.ExecuteNonQuery() > 0)
                {
                    MessageBox.Show("修改成功");

                }
                else
                {
                    MessageBox.Show("修改失败");
                }
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }
            finally
            {
                DBhelp.conn.Close();
            }
        }

Haga clic en el botón Cancelar y agregue un evento de clic:

 private void btnCollegeClose_Click(object sender, EventArgs e)
        {
            this.Hide();
        }

Cuando la página de configuración se selecciona inicialmente como ID de departamento, debe configurar la página para cargar el código frmCollege_Load:

private void frmCollege_Load(object sender, EventArgs e)
        {
            // TODO: 这行代码将数据加载到表“studentInfDataSet3.tb_College”中。您可以根据需要移动或删除它。
            this.tb_CollegeTableAdapter.Fill(this.studentInfDataSet3.tb_College);
            string conn = "Data Source=.;Initial Catalog=studentInf;Integrated Security=True";
            SqlConnection a = new SqlConnection(conn);

            try
            {
                a.Open();
                string sqlstr = string.Format("select * from tb_College where DepartmentName='医学院'");
                SqlCommand comm = new SqlCommand();
                comm.Connection = a;
                comm.CommandText = sqlstr;

                SqlDataReader read = comm.ExecuteReader();
                if (read.Read())
                {
                    txtCollegeNo.Text = read[0].ToString();
                }

                
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }
            finally
            {
                a.Close();
            }



            try
            {
                DBhelp.conn.Open();
                string sqlstr = "select * from tb_College";
                SqlDataAdapter datadapter = new SqlDataAdapter(sqlstr, DBhelp.conn);
                DataSet set = new System.Data.DataSet();
                datadapter.Fill(set);
                dataGridView1.DataSource = set.Tables[0];

            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }
            finally
            {
                DBhelp.conn.Close();
            }
        }

3. Cree una página para agregar estudiantes, frmAddStudent.cs:

 Agregue una etiqueta con el nombre del número de estudiante, cuadro de entrada Control de cuadro de texto Nombre Cuadro de entrada de etiqueta Cuadro de texto, agregue un contenedor de Panel y coloque dos controles de botón de radio Botón de radio con nombre masculino y femenino 

Agregue un control de etiqueta para nombrar la fecha de nacimiento y un control de cuadro de texto de cuadro de entrada

Agregue un control de etiqueta llamado: clase, agregue un control de cuadro desplegable Control ComboBox, haga clic en el triángulo pequeño sobre el control ComboBox, seleccione el elemento de enlace de datos de uso, enlace la tabla en la base de datos

... 

 Agregar dos botones Botón llamado, agregar, salir

Haga doble clic en el botón Agregar para agregar un evento de clic:

 private void btnAdd_Click(object sender, EventArgs e)
        {
            try
            {
                DBhelp.conn.Open();
                string sqlstr = string.Format("insert into tb_Student values('{0}','{1}','{2}','{3}','{4}','{5}','{6}')", txtstudentID.Text, txtStudentName.Text, radmale.Checked ? radFamale.Text : radmale.Text, txtBirthday.Text, cmbClassID.Text, txtMobilePhone.Text, txtAddress.Text);
                DBhelp.comm.CommandText = sqlstr;
                DBhelp.comm.Connection = DBhelp.conn;

                if ((int)DBhelp.comm.ExecuteNonQuery() > 0)
                {
                    MessageBox.Show("插入成功");

                }
                else
                {
                    MessageBox.Show("插入失败!");
                }
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }
            finally
            {
                DBhelp.conn.Close();
            }
        }

Haga doble clic en el botón de salida y agregue un evento de clic:

 private void btnClose_Click(object sender, EventArgs e)
        {
            this.Hide();
        }

Consulte el código de seguimiento: Sistema de gestión de información estudiantil - Código de sección 2

 

Supongo que te gusta

Origin blog.csdn.net/dengfengling999/article/details/123717619
Recomendado
Clasificación