如何数据控件外部,获得数据行的DataKeys?
以下代码,是通过遍历GridViewRow中的checked来确定选中的数据行,是否要被删除。
·但是我却不知道该怎么获得行的ID了?请高手指点!
------
protected void Button3_Click(object sender, EventArgs e)
{
foreach (GridViewRow gr in GridView1.Rows)
{
CheckBox chk = (CheckBox)gr.Cells[6].FindControl( "itemchk ");
if (chk.Checked)
{
string id =???
}
}
}
------解决方案--------------------你不会把e换为gr嘛。
------解决方案--------------------for (int i=0;i <GridView1.Rows.Count;i++)
{
CheckBox chk = (CheckBox)gr.Cells[6].FindControl( "itemchk ");
if (chk.Checked)
{
string id =GridView1.DataKeys[i].Values[0].ToString();
}
}
对了
------解决方案--------------------·根据前两位的提示,我把关于基于数据控件对象的Rows/column弄了个明白,其实非常简单,我以将两种方法分别实现了,如下:
---基于foreach的---
foreach (GridViewRow GR in GridView1.Rows)
{
CheckBox chk0 = (CheckBox)GR.Cells[6].FindControl( "itemchk ");
if (chk0.Checked)
{
string id = GridView1.DataKeys[GR.RowIndex].Values[0].ToString();
string sqlstr = "delete from authors where au_id= ' " + id + " ' ";
//以下数据操作可以封装到全局类
string constr = ConfigurationManager.ConnectionStrings[ "pubsConnectionString "].ConnectionString;
SqlConnection sqlCon = new SqlConnection(constr);
sqlCon.Open();
SqlCommand sqlCom = new SqlCommand(sqlstr, sqlCon);
sqlCom.ExecuteNonQuery();
}
}
---基于FOR的---
for (int i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox chk = (CheckBox)GridView1.Rows[i].Cells[6].FindControl( "itemchk ");
if (chk.Checked)
{
string id = GridView1.DataKeys[i].Values[0].ToString();
string sqlstr = "delete from authors where au_id= ' " + id + " ' ";
string constr = ConfigurationManager.ConnectionStrings[ "pubsConnectionString "].ConnectionString;
SqlConnection sqlCon = new SqlConnection(constr);
sqlCon.Open();
SqlCommand sqlCom = new SqlCommand(sqlstr, sqlCon);
sqlCom.ExecuteNonQuery();
}
}