【问题标题】:How to find row index with respect to datakey in GridView asp.net如何在 GridView asp.net 中查找关于数据键的行索引
【发布时间】:2012-06-22 22:27:20
【问题描述】:

我有一个启用分页的gridview控件,我有一个datakey值,我想找到一个关于datakey值的行索引,我有这个代码,

protected int GetRowIndex(object userID)
{
  for(int i = 0l i <= GridView1.DataKey.Count -1 ; i++)
  {
    if(GridView1.DataKey[i].Value == userID)
    {
       return i;
    }   

  }

}

但是这段代码存在问题,如果在该页面中找不到该用户 ID,它将返回 0,我的问题是如何更改页面索引以在所有页面中查找行。我使用的是自己的 gridview分页。

【问题讨论】:

    标签: asp.net c#-4.0 gridview datakey


    【解决方案1】:

    没有对此的直接支持,因为 GridView 没有将所有 DataKeys 存储在某个地方以供其搜索。它仅保留用于当前页面的一组 DataKey。更改页面索引不会自动“加载”该页面的 DataKey,以便您可以搜索每个。

    您必须通过添加一个函数来解决这个问题,当给定用户 ID 时,该函数将返回要显示的页面。它可能被命名为 GetPageFromUserID(object userID)。此函数需要使用与网格相同的排序顺序、页面大小和过滤条件来搜索您的数据存储。

    即使使用您将设置到 GridView.PageIndex 属性中的页面索引,您仍然必须在 GridView 上调用 DataBind() 才能使其从数据库,以便您可以使用上面的代码来查找行索引。

    【讨论】:

      【解决方案2】:
          private static int IndexOfGridView(GridView gridView, int dataKeyId, int index)
          {
              foreach (GridViewRow gvRow in gridView.Rows)
              {
                  var dataKey = gridView.DataKeys[gvRow.DataItemIndex];
                  if (dataKey == null || (int)dataKey.Value != dataKeyId) continue;
                  index = gvRow.DataItemIndex;
                  break;
              }
              return index;
          }
      

      【讨论】:

        【解决方案3】:

        您可以通过以下方式在 GridView 中找到行索引:

        rowIndex = theGridView.DataKeys.IndexOf(theDataKeyValue)
        

        我在一个我们仍在维护的旧 ASP.net VB 项目中发现了这个,希望对您有所帮助。

        【讨论】:

          【解决方案4】:
          string user_id = GridView1.SelectedDataKey["userID"].ToString();
          

          在这里您可以在网格视图中获取所选数据的用户 ID

          <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
                    DataKeyNames="userID" OnRowDataBound="GridView1_RowDataBound"
                          OnSelectedIndexChanged="GridView1_SelectedIndexChanged" >
          
             <asp:CommandField ShowSelectButton="True"> </asp:CommandField>
          
              // write code
          
            </asp:GridView>
          

          你在 Gridview 中做分页概念,它最好在后端本身做,然后你会很容易显示数据,即你一次取 10 个数据,同时点击第一页,就像我做的一样。在中继器中,这与 gridview 相比很容易......

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2016-10-11
            • 1970-01-01
            • 2022-11-11
            • 1970-01-01
            • 2023-04-07
            • 2020-01-19
            • 1970-01-01
            • 2014-11-12
            相关资源
            最近更新 更多