代码之家  ›  专栏  ›  技术社区  ›  Thomas

GridView分页,无法获取正确的数据键值

  •  2
  • Thomas  · 技术社区  · 15 年前

    GRIDVIEW

    <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" />
    

    对于加载的第一页,如果单击命令字段,它将显示正确的数据键值。

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

    编辑:

    在GridView中,我使用了以下方法:

        // 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>");
    

    分页后无法获得正确的值。

    3 回复  |  直到 12 年前
        1
  •  2
  •   Erik Schierboom    12 年前

    使用分页时,我们可以得到精确的行索引(从0到 totalrows 在GRIDVIEW中) 当提取时 datakey ,我们需要传递当前页的行索引。

    使用下面的行获取当前页索引并获取数据键:

    // Get the correct row index since there is paging
    int idx = gridViewRow.DataItemIndex - TestGridView.PageIndex * TestGridView.PageSize;
    
        2
  •  1
  •   Kyaw Thura    14 年前

    我可能会迟到。 但对于其他人,我会回答这个问题。

    “在使用Datakey数组之前重新绑定GridView”

    它对我有用。 希望对其他人也有用。

        3
  •  0
  •   Thomas    14 年前

    不久前修好了。正在使用第三方网格视图帮助程序类。这打破了网格视图的正常功能。