2010-08-05 60 views
2

的GridViewGridView的分页,无法得到正确的Datakey价值

<asp:GridView ID="GridView1" runat="server" AllowPaging="True" 
    AllowSorting="True" PagerSettings-Position="TopAndBottom" 
    PagerSettings-Mode="Numeric" PageSize="40" CellPadding="4" DataSourceID="dsEquipmentGridView" 
    ForeColor="#333333" GridLines="Horizontal" Style="font-size: x-small" AutoGenerateColumns="False" 
    DataKeyNames="IREF" OnRowEditing="GridView1_RowEditing" OnRowUpdated="GridView1_RowUpdated" 
    OnSorted="GridView1_Sorted" OnSorting="GridView1_Sorting" OnPageIndexChanged="GridView1_PageIndexChanged1" 
    OnPageIndexChanging="GridView1_PageIndexChanging" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" 
    OnSelectedIndexChanging="GridView1_SelectedIndexChanging" OnRowCommand="GridView1_RowCommand" 
    BorderColor="Black" BorderStyle="Solid" BorderWidth="1px" 
    OnRowCancelingEdit="GridView1_RowCancelingEdit" onload="GridView1_Load" 
    ondatabound="GridView1_DataBound"> 
    <PagerSettings Position="TopAndBottom" /> 
    <RowStyle BackColor="#F7F6F3" ForeColor="#333333" /> 
    <Columns> 
<asp:CommandField ShowDeleteButton="False" ShowSelectButton="true" EditText="QuickEdit" 
    HeaderText="Manage" SelectText="Manage" /> 

对于加载的第一页,它显示了正确的DataKey值,如果我点击命令字段。

但是,如果我切换到结果的下一页,在选择记录时,对应的值不正确。它似乎保留了上一页的信息。我如何克服这一点?

编辑:

在GridView1_SelectedIndexChanged方法,我用了以下内容:

// Determine the index of the selected row. 
    int index = GridView1.SelectedIndex; 

    // Display the primary key value of the selected row. 
    HttpContext.Current.Response.Write("The primary key value of the selected row is " + GridView1.DataKeys[index].Value.ToString() + ".<br>"); 

    GridViewRow row = GridView1.Rows[index]; 

    int rowindex = row.RowIndex; 
    HttpContext.Current.Response.Write("rowindex-> " + rowindex.ToString() + "<br>"); 

    int ID = (int)GridView1.DataKeys[row.DataItemIndex - (GridView1.PageIndex * GridView1.PageSize)].Value; 

    HttpContext.Current.Response.Write("row.DataItemIndex" + ID.ToString()+"<br>"); 

    int Userid = Convert.ToInt32(GridView1.DataKeys[index].Value); 

    HttpContext.Current.Response.Write("Userid" + Userid.ToString() + "<br>"); 

我无法得到传呼后,正确的值。

回答

0

前一段时间修复。正在使用第三方GridView辅助类。这打破了GridView的正常功能。

1

我可能会迟到。 但对于其他人,我回覆。

它为我的作品 “使用DataKey阵列之前,再次重新绑定gridview的”。 希望它也适用于其他人。

2

当使用分页,我们能得到确切的行索引(从0开始计数到totalrows在GridView控件) 和获取datakey时,我们需要传递当前页的行索引。

使用下面的一行来获得当前的页面索引,并获得datakey:

// Get the correct row index since there is paging 
int idx = gridViewRow.DataItemIndex - TestGridView.PageIndex * TestGridView.PageSize;