您的位置:首页 > 其它

在GridView的RowCommand事件中取得相应的行号,主键值与某行某列的值

2009-12-29 22:14 441 查看
前台GridView中模板列的代码如下 ,在GridView中添加了一个模板列,模板列中放了一个ImageButton按钮,如下:

<asp:TemplateField HeaderText="管理">
<ItemTemplate>
<asp:ImageButton ID="imgBtnManage" runat="server" CommandName="manage" CommandArgument='<%# Eval("ProductID") %>' ImageUrl="~/Images/manage_25X25.gif" />
</ItemTemplate>
</asp:TemplateField>

第一种方式,取得点击的行号,主键值,某行中指定列的值,如下:

protected void gvProduct_RowCommand(object sender, GridViewCommandEventArgs e)
{

  int index = ((GridViewRow)((ImageButton)(e.CommandSource)).Parent.Parent).RowIndex;//获取当前点击前的行号 ,说明:ImageButton因为我     // 放的按钮为ImageButton,用户可以根据放置的控件不同而不同。
string key = this.gvProduct.DataKeys[index].Value.ToString();//获取当前选点击行的主键值
string id = this.gvProduct.Rows[index].Cells[1].Text;//获取当前点击行,某列的值

/*

  补充一下,因为我在上面的前台代码中放了CommandArgument='<%# Eval("ProductID") %>',ProductID为数据库中的主键,所以得到主键值也可以如下:string strProductId = e.CommandArgument.ToString();

*/

// 有了上面的操作,以下操作就方便了

  if (e.CommandName == "manage")
{

    //.......

  }

}

第二种方式:

//在前台代码中,不要 CommandArgument='<%# Eval("ProductID") %>' 这个代码,即去掉这个,然后,下面操作:

protected void gvProduct_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "manage")
{
int index = Convert.ToInt32(e.CommandArgument);
string key = this.gvProduct.DataKeys[index].value.toString();
Response.Write(key);
}
}

//行数据绑定
protected void gvProduct_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
ImageButton imgBtn = new ImageButton ();
imgBtn = (ImageButton )e.Row.Cells[6].FindControl("imgBtnManage");//自己清楚,此ImageButton模板列,你放在GridView中的第几列。
imgBtn .CommandArgument = e.Row.RowIndex.ToString();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: