现在的位置: 首页 > 综合 > 正文

GridView各个事件中,怎样获取主键值

2013年12月03日 ⁄ 综合 ⁄ 共 1924字 ⁄ 字号 评论关闭

自动编号

首先我们为 Gridview 增加一个新的空白列,如下:
<asp:BoundField HeaderText="序号">
            <ItemStyle HorizontalAlign="Center" Width="26px" />
            </asp:BoundField>

在 GridView RowDataBound 事件中编写代码,如下:
protected void RowDataBond1(object sender, GridViewRowEventArgs e)
{
         if (e.Row.RowIndex > -1)
        {
         
         e.Row.Cells[0].Text = Convert.ToString(e.Row.RowIndex + 1);
        }
          
}

PS:还有种常用的方法是利用asp:TemplateField 自定义一列:
<asp:TemplateField HeaderText="序号">           
                <ItemTemplate>             
               &nbsp; <asp:Label ID="lab_index" runat="server" Text="<%#Container.DataItemIndex+1%>"></asp:Label>
                </ItemTemplate>
                    <ItemStyle Width="40px" />
                </asp:TemplateField>

       这样就会有一个自动编号的列出来了,那么我们要对某一列进行操作的时候就不能用cells[0].text的方法了,那样得到的ID号和数据库里的并不对应,所以我们要用主键的方法,我们首先在GridView的属性中的DataKeyNames里面写上我的的表主键,然后在到方法里用语句把这个值取出来,我们就知道用户是要对哪一列进行操作了,下面写出了几个在事件中取出主键值的方法,以供参考。

我们最常用的,当然就是RowDataBound方法了

在 GridView1_RowDataBound获取主键的值
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
     int index = GridView1.DataKeys[e.Row.RowIndex].Value;
}

其次就是删除事件

在 GridView1_RowDeleting获取主键的值
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
     int
index
=GridView1.DataKeys[e.RowIndex].Value;
}

分页事件

在 GridView1_PageIndexChanging获取主键的值

protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
     int index=GridView1.DataKeys[e.NewPageIndex].Value;
}

还有其它几个不常用的:

在 GridView1_RowCommand中获取主键的值:

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
        int index = GridView1.DataKeys[Convert.ToInt32(e.CommandArgument)].Value;
}

在 GridView1_RowEditing获取主键的值
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
      int index = GridView1.DataKeys[e.NewEditIndex].Value;
}

在 GridView1_RowUpdating获取主键的值

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
      int index = GridView1.DataKeys[e.RowIndex].Value;
}

抱歉!评论已关闭.