如何使用复选框列从DataGridView中删除多个项目
本文关键字:删除 项目 DataGridView 何使用 复选框 | 更新日期: 2023-09-27 18:18:46
这是加载DataGridView
的代码。
private void btnLoaddata_Click(object sender, EventArgs e)
{
AddCheckBoxforDataGridView();
try
{
conDB.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = conDB;
command.CommandText = "select CWDetails,CCSpn_CODE as 'SPN CODE',CCFname as 'First Name',CCLname as 'Last Name',CCMname as 'Middle Name',CCDOB as 'Date Of Birth',CCgender as 'Gender',CCSchool as 'School',CaClass as 'Class',CCVillage as 'Village',CCSiblings as 'Number Of Siblings',CCGuardian as 'Guardian',CCContact as 'Contact',CCcurrentDt as 'Date Of Entry' from abaanaCC";
// command.Parameters.Add(new OleDbParameter("@IMG", imageBt));
// command.ExecuteNonQuery();
//MessageBox.Show("Record Saved");
OleDbDataAdapter da = new OleDbDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
EditdataGridView1.DataSource = dt;
}
catch (Exception ex)
{
MessageBox.Show("Unable to Load Data");
}
conDB.Close();
}
下面的代码将checkbox
列添加到DataGridView
private void AddCheckBoxforDataGridView()
{
DataGridViewCheckBoxColumn col = new DataGridViewCheckBoxColumn()
{
Name = "Check"
};
EditdataGridView1.Columns.Add(col);
}
这是为删除而创建的方法。CWDetails
列是数据库
primary key
。public int DeleteMult(int CWDet)
{
conDB.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = conDB;
string query = "delete from abaanaCC where CWDetails = " + CWDet + "";
command.CommandText = query;
int res = command.ExecuteNonQuery();
conDB.Close();
return res;
}
下面是删除按钮del_Mult
的代码,它不起作用
private void del_Mult_Click(object sender, EventArgs e)
{
DataGridViewRow row = new DataGridViewRow();
for (int i = 0; i < EditdataGridView1.Rows.Count; i++)
{
row = EditdataGridView1.Rows[1];
if (Convert.ToBoolean(row.Cells[0].Value) == true)
{
int id = Convert.ToInt16(row.Cells[1].Value);
DeleteMult(id);
EditdataGridView1.Rows.Remove(row);
i++;
}
}
}
您也可以尝试在foreach循环中这样做,这样您就不必与int i
混淆,像这样:
private void del_Mult_Click(object sender, EventArgs e)
{
List<DataGridViewRow> deleteRows = new List<DataGridViewRow>();
foreach(DataGridViewRow row in EditdataGridView1.Rows)
{
if(Convert.ToBoolean(row.Cells[0].Value) == true)
{
int id = Convert.ToInt16(row.Cells[1].Value);
DeleteMult(id);
deleteRows.Add(row);
}
}
foreach(DataGridViewRow row in deleteRows)
{
EditdataGridView1.Rows.Remove(row);
}
}
尽管您必须创建要删除的行列表,因为当您忙于遍历它们时无法删除它们
您没有使用i检索网格行。你也不需要i++,因为你已经在for循环中做了。
row = EditdataGridView1.Rows[i];
删除我+ + 声明如果。