1

i have a gridview control in which paging is enabled, i have a datakey value,i want to find a row index with respect to datakey value ,i have this code,

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

  }

}

but there is problem with this code, that if that user id is not found in that page it will return 0, my question is that how can i change the page index to find row in all pages.i am using gridview own paging.

Salman Roy
  • 555
  • 1
  • 11
  • 26

4 Answers4

2

There is no direct support for this, because the GridView doesn't have all of the DataKeys stored away somewhere for it to search. It keeps only the set of DataKeys that it uses for the current page. Changing the page index does not automatically "load" the DataKeys for that page so that you can search each one.

You will have to solve this by adding a function which, when given a userID, will return the page to display. It might be named GetPageFromUserID(object userID). This function will need to search your data store, using the same sort order, page size, and filter conditions as your grid.

Even with that page index, which you'll set into the GridView.PageIndex property, you'll still have to call DataBind() on the GridView in order to get it to load the rows (and the DataKeys) from the database so that you can use the code you have above to find the row index.

Alan McBee
  • 3,859
  • 3
  • 27
  • 38
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;
    }
0

You may find the row index in the GridView with:

rowIndex = theGridView.DataKeys.IndexOf(theDataKeyValue)

I found this on an old ASP.net VB project we're still maintaining, hope it helps.

-1
string user_id = GridView1.SelectedDataKey["userID"].ToString();

Here you get the Userid of the Selected Data in a gridview

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

U r doing Pagination concept in Gridview, its better do in backend itself, then it will easy for u to display Data i.e u take 10 data at a time while click on first page like wise.. the same concept i have done in repeater which is easy when compare to gridview...

Prince Antony G
  • 912
  • 4
  • 18
  • 38