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

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

2013年05月08日 ⁄ 综合 ⁄ 共 2106字 ⁄ 字号 评论关闭

平时用GridView做信息列表后台的时候,前面通常都加一个序号列。此时就不能用数据库里的ID号了,因为数据库的删除插入操作,导致那些号码并不连贯,给人的感觉不是很好,所以这里通常让他自动编号。

首先我们为 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;
 }

 

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/dongxinxi/archive/2009/07/28/4386399.aspx

抱歉!评论已关闭.