这里的代码加载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++;
}
}
}
答案 0 :(得分:0)
您没有使用 i 来检索网格行。此外,您不需要 i ++ ,因为您已经在for循环中执行此操作。
row = EditdataGridView1.Rows[i];
如果条件,请从中删除 i ++ 语句。
答案 1 :(得分:0)
您也可以尝试在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);
}
}
虽然您必须列出要删除的行,但由于在繁忙迭代行时无法删除行。