[size=small]
遍历获取ID
1、前台设置
2、后置代码
[/size]
protected void Page_Load(object sender, EventArgs e)
{
DataBindToGridView();
}
public void DataBindToGridView()
{
SqlConnection con = DataConnection.createCon();
SqlDataAdapter sda = new SqlDataAdapter("select * from Demo", con);
con.Open();
DataSet ds = new DataSet();
sda.Fill(ds, "Demo");
this.GridView1.DataKeyNames = new string[] { "ID" };
this.GridView1.DataSource = ds;
this.GridView1.DataBind();
con.Close();
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#D2BF8C'");//设置鼠标经过时的背景色
e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");//设置鼠标离开时的背景色
e.Row.Attributes["style"] = "Cursor:hand"; //设置悬浮鼠标指针形状为"小手"
//遍历GridView所有的行
for (int i = 0; i < GridView1.Rows.Count; i++)
{
//读取该行ID为"lable1"的控件
Label lable1 = GridView1.Rows[i].FindControl("lable1") as Label;
//判断该控件的显示文本
if (lable1.Text == "待审核")
{
//相应处理
}
}
}
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
SqlConnection con = DataConnection.createCon();
int ID = int.Parse(GridView1.DataKeys[e.RowIndex].Values[0].ToString());
string sql = "Delete From Demo Where ID=" + ID + "";
SqlCommand cmd = new SqlCommand(sql, con);
con.Open();
cmd.ExecuteNonQuery();
DataBindToGridView();
}
遍历获取ID
1、前台设置
<asp:GridView ID="GridView1" runat="server" DataKeyNames="Id">
2、后置代码
//方法一
for (int i = 0; i < GridView1.Rows.Count; i++)
{
string Id = GridView1.DataKeys[i].Value.ToString();
}
//方法二
foreach (GridViewRow row in GridView1.Row)
{
string Id = GridView1.DataKeys[row.RowIndex].Value.ToString();
}
[/size]