gridview 获取主键的方法

来源:互联网 发布:青少年编程 加盟 编辑:程序博客网 时间:2024/05/18 00:09

1. RowCommond 事件

.aspx

在GridView添加一模板列,加上CommandArgument 并绑定如下

  1. <asp:GridView ID="gvAdminList" runat="server" >            
  2.  <asp:TemplateField>
  3.    <ItemTemplate>
  4.       <asp:LinkButton ID="lbtnLook" runat="server" CommandName="GetAdminInfo" CommandArgument='<%# Eval("AdminID") %>'>查看</asp:LinkButton>
  5.       </ItemTemplate>
  6.    </asp:TemplateField>
  7.   </asp:GridView>

.aspx.cs

读取CommandArgument

  1. protected void gvAdminList_RowCommand(object sender, GridViewCommandEventArgs e)
  2.  {
  3.   if (e.CommandName == "GetAdminInfo")
  4.      {
  5.      string AdminID = e.CommandArgument.ToString();
  6.      }
  7.  }

这个事件是我们常用的获取主键的方法,通过为按钮设置 commandname和 commandargument ,前者是用来区别点了哪个按钮,后者则是按钮所代表的参数,利用绑定,很容易获取了要操作行的主键