Modify the data in the DataGridView and update to the sql database

Implementation idea:
modify the data in the DataGridView, first pop up the modification interface, display the information before modification, and then on the modification page, modify and update to the database

**

1. Click "Modify" to pop up the modification interface and display the information of the selected middle row on the interface

**

  • Click "Modify" in the page, the modification page pops up, and the information of the row to be modified is automatically displayed in the modification pageInsert picture description here
  • Implementation process:
    1. Click "Modify" to obtain the student number selected by the mouse, and transfer the value to a new form (information modification interface). The new form reads the database and loads the relevant information according to the StuId student number.
    Note: Set the modification interface as the parent form of the current "student list" so that the page is displayed in the main interface
    frmEditStudent.Tag is the data object of the interface, object type
//1 获取我当前点击的单元格的行列数索引
//2 判断是否选择的是link列,并且判断是 删除还是修改
DataRow dr = (dgvStudents.Rows[e.RowIndex].DataBoundItem as DataRowView).Row;
DataGridViewCell cell = dgvStudents.Rows[e.RowIndex].Cells[e.ColumnIndex];
if (cell is DataGridViewLinkCell && cell.FormattedValue.ToString() == "修改")
{
    //修改操作,打开修改页面,并把stuId传过去
    //传值法:tag属性
    int stuId = (int)dr["StuId"];
    FrmEditStudent frmEditStudent = new FrmEditStudent();
    frmEditStudent.Tag = stuId;//这里用的是tag属性传值
    frmEditStudent.MdiParent = this.MdiParent;//指定修改页面的父容器
    frmEditStudent.Show();//显示在MDI窗体内
}

In the new form interface, form loading function;

 private void FrmEditStudent_Load(object sender, EventArgs e)
 {
     MessageBox.Show("您要修改的信息的学生学号为"+ "\n" + this.Tag.ToString(), "温馨提示");
     InitClasses();//加载班级列表
     InitStuInfo();//加载学生信息
 }

The student ID of the first row of data clicked is 1002, then 1002 is the value of the tag attribute passed in for debugging.
Insert picture description here
Insert picture description here
First, load the class list; the class table and grade table are as follows:
query statement
select ClassId,ClassName,GradeName from ClassInfo c,GradeInfo g where c.GradeId = g.GradeIdInsert picture description here
query results:
Insert picture description here
ideas: create a query through the sql statement, read the data in the database, and save it as a DataTable type, and then send the information to the combox designated data source display

//--------------加载班级列表-----------------------------------
private void InitClasses()
{
    //获取数据 联合查询
    string sql = "select ClassId,ClassName,GradeName from ClassInfo c,GradeInfo g where c.GradeId = g.GradeId";
    DataTable dtClasses = SqlHelper.GetDataTable(sql);//把数据库中的数据读出来,存为DataTable类型
    //组合班级列表显示项 遍历过程
    if (dtClasses.Rows.Count > 0)
    {
        foreach (DataRow dr in dtClasses.Rows)
        {
            string className = dr["ClassName"].ToString();
            string gradeName = dr["GradeName"].ToString();
            dr["ClassName"] = className + "  " + gradeName;
        }
    }
    //指定数据源 并显示
    cboClasses.DataSource = dtClasses;
    cboClasses.DisplayMember = "ClassName";
    cboClasses.ValueMember = "ClassId";
}

Load student information:
If the tag attribute (ie the student ID is not empty) is transferred, the passed student ID is converted to int type,
and then a query is created from the student table, and the data is read and displayed one by one. Note the usage of ExecuteReader here
ExecuteReader queries the database as fast as possible and gets the result. Return a SqlDataReader object
CommandBehavior.CloseConnection: Do not close the database connection before returning the object

Reference blog: https://www.cnblogs.com/st2012/archive/2012/04/06/2435406.html

//---------------------加载学生信息------------------------
private void InitStuInfo()
{
    if (this.Tag != null && this.Tag.ToString()!="")
    {
        int.TryParse(this.Tag.ToString(), out stuId);
    }
    //查询数据
    string sql = "select StuName,Sex,ClassId,Phone from StudentInfo where StuId=@StuId";
    SqlParameter paraId = new SqlParameter("@StuId",stuId);
    SqlDataReader dr = SqlHelper.ExecuteReader(sql,paraId);
    //读取数据 数据读取流只能向前不能后退,读一条丢一条
    if (dr.Read())
    {
        txtStuName.Text = dr["StuName"].ToString();
        txtPhone.Text = dr["Phone"].ToString();
        string sex = dr["Sex"].ToString();
        int classId = (int)dr["ClassId"];
        if (sex == "男")
        {
            rbtMale.Checked = true;
        }
        else
        {
            rbtFemale.Checked = true;
        }
        cboClasses.SelectedValue = classId;
    }
    dr.Close();
}
/// <summary>
/// 执行查询,返回 SqlDataReader 数据库读取的行数据流zyh
/// </summary>
/// <param name="sql"></param>
/// <param name="paras"></param>
/// <returns></returns>
public static SqlDataReader ExecuteReader(string sql,params SqlParameter[] paras)
{
    //打开数据库
    SqlConnection conn = new SqlConnection(connString);
    try
    {
        conn.Open();
        SqlCommand cmd = new SqlCommand(sql, conn);
        cmd.Parameters.Clear();
        cmd.Parameters.AddRange(paras);
        SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
        return dr;
    }
    catch (SqlException ex)
    {
        conn.Close();
        throw new Exception("执行查询出现异常",ex);
    }           
}

The next step is to click the "modify" button to update the modified data to the database

Published 18 original articles · praised 0 · visits 233

Guess you like

Origin blog.csdn.net/qq_39217004/article/details/105396237