日期:2014-05-18  浏览次数:20406 次

关于datagrid中删除checkbox被选中项的问题
关于datagrid中删除checkbox被选中项的问题
网上有很多例子·我都尝试了下·
可能是我水平有限·特别是删除的具体代码弄不懂
请高手给个简单好用的代码·


------解决方案--------------------
private void btnDelete_Click(object sender, System.EventArgs e)
{
string whereClause = string.Empty;
foreach(DataGridItem dgi in DataGrid1.Items)
{
CheckBox chk = (CheckBox)dgi.FindControl( "chkSelect ");
if(chk != null)
{
if(chk.Checked)
{
if(whereClause == string.Empty)
whereClause += " ' " + DataGrid1.DataKeys[dgi.ItemIndex].ToString() + " ' ";
else
whereClause += ", ' " + DataGrid1.DataKeys[dgi.ItemIndex].ToString() + " ' ";
}
}
}
if(whereClause != string.Empty)
{
SqlConnection cn = new SqlConnection( "server=.;uid=sa;pwd=;database=pubs ");
string strSQL = "delete from authors where au_id in ( " + whereClause + ") ";
SqlCommand cmd = new SqlCommand(strSQL, cn);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
BindGrid();//重新绑定DataGrid
}
------解决方案--------------------
protected void btnDelete_Click(object sender, System.EventArgs e)
{
foreach(DataGridItem item in DataGrid1.Items)
{
CheckBox chk = dgi.FindControl( "MyCheckBoxIDNestedInDataGridItemTemplate ") as CheckBox;
if(chk != null && chk.Checked)
{
object key = DataGrid1.DataKeys[item.ItemIndex]; // 获取主键
// 数据库操作 ....
// ....
}
}
}