Delete multiple rows of data in DataGridView and update to sql database

The previous blog post introduced the deletion of data in DataGridView in detail, and the demonstrations were based on true deletion and false deletion. For details, please refer to:
https://blog.csdn.net/qq_39217004/article/details/105366769

Delete multiple rows of data in DataGridView and update to sql database

The following demonstrates the implementation of multi-line deletion of data on the control: (indicated by the false deletion bit column, true deletion only needs to change the sql statement)
The results of the demonstration will be described later, first look at the implementation process:
// Mouse selection to delete The data
// Get the StuId of the data to be deleted
// Judge the number of choices, if the number of choices is greater than 0, delete, otherwise it prompts that no selection
// delete operation starts the transaction in the code

1. Use the mouse to select the data to be deleted and obtain the StuId of the data to be deleted

 List<int> listIds = new List<int>();//定义一个泛型 存储要删除的Id号
 for (int i = 0; i < dgvStudents.Rows.Count; i++)//遍历表中的所有行数,获取选中的行数据
 {
     DataGridViewCheckBoxCell cell = dgvStudents.Rows[i].Cells["colCheck"] as DataGridViewCheckBoxCell;//获取复选框
     //若cell.Value值为 null,即没选中任何行,则chk为false,否则只要选中了某一行,则返回true
     bool chk = Convert.ToBoolean(cell.Value);//若选中的数量不为0
     if (chk)
     {
         //获取行数据并把数据存储在listIds泛型中
         DataRow dr = (dgvStudents.Rows[i].DataBoundItem as DataRowView).Row;
         int stuId = (int)dr["StuId"];
         listIds.Add(stuId);
     }
 }

2. Judge the number of choices, if the number of choices is greater than 0, delete, otherwise it prompts that you did not choose to
use the SqlTransaction class to start a transaction, the following is a fixed usage, specific reference link
/https://docs.microsoft.com/zh-cn /dotnet/api/system.data.sqlclient.sqltransaction?view=netframework-4.8

  using (SqlConnection conn =new SqlConnection(SqlHelper.connString))
 {
     //事务启动是通过conn来开启
     conn.Open();
     SqlTransaction trans = conn.BeginTransaction();//开启一个事务
     SqlCommand cmd = new SqlCommand(); //利用SqlCommand执行事务
     //固定用法
     //为挂起的本地事务将事务对象和连接都分配给命令对象
     cmd.Connection = conn;
     cmd.Transaction = trans;
  }

First, traverse the generic class, pass the parameters to SqlParameter, and then commit the transaction and return the number of rows affected;
note that the exception catch in the catch has the following statement, which is the usage provided by Microsoft
trans.Rollback (); // catch specific Usage, roll back the transaction from the suspended state
Note: It
must be cleared every time the loop passes parameters;

 try
 {                          
     foreach (int id in listIds)
     {
         //cmd.CommandText = "delete from StudentInfo where StuId=@StuId";//真删除
         cmd.CommandText = "update StudentInfo set IsDeleted=1 where StuId=@stuId";//假删除
         SqlParameter para = new SqlParameter("@StuId",id);
         cmd.Parameters.Clear();
         cmd.Parameters.Add(para);
         count += cmd.ExecuteNonQuery();
     }
     trans.Commit();//提交事务,代表所有的事务已经提交到数据库
     Console.WriteLine("Both records are written to database.");
 }
 catch (SqlException ex)
 {
     trans.Rollback();//catch特定用法,从挂起状态滚回事务
     MessageBox.Show(ex.Message, "删除学生信息提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
     return;
 }

If the number of affected rows returned above is the same as the value in the generic class (the number of rows you manually selected), you are prompted to delete successfully; and delete the selected information in datagridview

if (count == listIds.Count)
{
    MessageBox.Show("选中的学生信息删除成功", "删除学生信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
    //列表的手动刷新
    DataTable dtStudents = (DataTable)dgvStudents.DataSource;//获取数据源
    string idStr = string.Join(",",listIds);
    DataRow[] rows = dtStudents.Select("StuId in (" + idStr + ")");
    foreach (DataRow dr in rows)
    {
        dtStudents.Rows.Remove(dr);
    }
    dgvStudents.DataSource = dtStudents;
}

Note that the method of removing the selected information:

//是把选中的信息用,做字符串分隔,
string idStr = string.Join(",",listIds);
//要用来筛选行的条件    具体请参考ataView RowFilter 语法
DataRow[] rows = dtStudents.Select("StuId in (" + idStr + ")");

For example, after selecting 1002 1004 1005 (StuId) three lines of information
, after executing this sentence,

idStr =1002,1004,1005//筛选条件
"StuId in "1002,1004,1005""

Insert picture description here
At this point, the code process has been shown

The following is a demonstration of the results achieved:

1. Initial information in the database
Insert picture description here
2. Load information
on the host computer interface Select the number of rows to be deleted in the checkbox, click the "Delete" button, and then click "OK"
Insert picture description here
3. The three rows of selected data on the interface disappear
Insert picture description here
4. Check the database Information, click "Execute", you can see that the selected three rows of data flags are already 1, which means that the false deletion is successful.
Insert picture description here
5. When the program is started again, the deletion is that the information will not be displayed on the interface.
Insert picture description here

At this point, the function of deleting multiple lines of information has been fully realized;
you are welcome to criticize and correct! !

Published 18 original articles · praised 0 · visits 233

Guess you like

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