public void btnDelete(object sender,System.EventArgs e)
{
//string dID;
//string strsql;
foreach (DataGridItem dgi in DataGrid1.Items)
{//轮询,选中的则删除
CheckBox cb = (CheckBox)dgi.FindControl("cbItem");
if(cb.Checked)
{
string dID = dgi.Cells[0].Text;
string strsql = "DELETE FROM person WHERE uid ='"+dID+"'";
ExecuteSql(strsql);
}
}
DataGrid1.CurrentPageIndex = 0;
BindData();
}
这段程序会出现"集合已更改,枚举类型不可能不可用"
这是因为一边轮询一边删除,造成集合的更改,也就是类似于for(int i = 0; i<count; i++)而count是一个变量,所以会出错
解决方法,找一个数组,把要删除的记录下来,然后在删除!
下面是修改后的代码
public void btnDelete(object sender,System.EventArgs e)
{
string[] dID;
dID = new string[DataGrid1.Items.Count];//预分配为全部删除
int count=0;//记录被选中的数目
int i = 0;
string strsql;
foreach(DataGridItem dgi in DataGrid1.Items)
{//轮询,把要删除的记录在一个表中
CheckBox cb = (CheckBox)dgi.FindControl("cbItem");
if(cb.Checked)
{
dID[i] = dgi.Cells[0].Text;
count++;
i++;
}
}
for(i = 0;i < count;i++)
{//轮询,删除所选项
strsql = "DELETE FROM person WHERE uid = '"+dID[i]+"'";
ExecuteSql(strsql);
}
DataGrid1.CurrentPageIndex = 0;
BindData();
}