views:

5480

answers:

4

I want something similar to the following pseudocode:

myGridView.SelectedIndex = myGridView.DataKeys.IndexOf("mySpecificKey");

I've done some Intellisense exploring, but I haven't found an obvious way to do this. I would want to set SelectedIndex to -1 if DataKey was not found.

+1  A: 

I've ended up with

        For n As Integer = 0 To myGridView.DataKeys.Count - 1
            If myGridView.DataKeys(n).Value = myKeyObj Then
                myGridView.SelectedIndex = n
            End If
        Next
Larsenal
+1  A: 
//grab the current datakeyValue
 int orderID = (int)this.GridView1.SelectedDataKey.Value;

//do something 
gridView.databind();

//set back the selected row int the gridView
 for (int i = 0; i < this.GridView1.DataKeys.Count - 1; i++)
 {
   if ((int)GridView1.DataKeys[i].Value == orderID)
    {
       this.GridView1.SelectedIndex = i;
   }
}
Johan
+2  A: 

Have you considered a Linq approach?

Usage:

GridView1.SelectedIndex = GridView1.DataKeys.IndexOf(id);

Code:

public static class WebControlsEx
{
    public static int IndexOf(this DataKeyArray dataKeyArray, object value)
    {
     if (dataKeyArray.Count < 1) throw new InvalidOperationException("DataKeyArray contains no elements.");
     var keys = dataKeyArray.Cast<DataKey>().ToList();
     var key = keys.SingleOrDefault(k => k.Value.Equals(value));
     if (key == null) return -1;
     return keys.IndexOf(key);
    }
}
Mark Good
+1  A: 

Your method above only searches the current page of the GridView, if paging is enabled. To search the entire GridView, you need to look into its DataSource and use that to get the appropriate values.

In my case, I needed to give users a quick way to search for a specific client, so I added an AJAX enabled Combo Box, and OnSelectedIndexChanged, I used this to locate the appropriate GridView row and select it:

        Dim i As Integer, DataSetIndex As Integer
        Dim SelectedRowIndex As Integer
        Dim dv As DataView = ObjectDataSourceClients.Select
        Dim dt As DataTable = dv.ToTable

        For i = 0 To dt.Rows.Count - 1
            If dt.Rows(i)("Client_ID") = ComboBoxClientSearch.SelectedValue Then
                DataSetIndex = i
                Exit For
            End If
        Next

        GridViewAllClients.PageIndex = DataSetIndex \ GridViewAllClients.PageSize
        SelectedRowIndex = DataSetIndex - (GridViewAllClients.PageSize * GridViewAllClients.PageIndex)
        GridViewAllClients.SelectedIndex = SelectedRowIndex

        GridViewAllClients.DataBind()
Phil
http://atominnovation.blogspot.com/2010/01/aspnet-search-gridview-and.html
Phil