11

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.

9 Answers 9

12

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
7

This works and it's nice and short:

        int MyId = 22;

        foreach (GridViewRow gvRow in gridview1.Rows)
        {
            if ((int)gridview1.DataKeys[gvRow.DataItemIndex].Value == MyId)
            {
                gridview1.SelectedIndex = gvRow.DataItemIndex;
                break;
            }
        }
6

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);
    }
}
4
  • 1
    Could use a touch of white-space, but this is quite nice.
    – Kirk
    Sep 15, 2011 at 21:03
  • All this extension method will do is always return -1. DataKeyArray doesn't have an IndexOf() method, the only reason it compiles is because your extension method is named IndexOf. So when the first return keys.IndexOf(key) line is reached, it will call the same method again, only this time, the value parameter will be an instance of a DataKey. Which in turn won't satisfy the k.Value.Equals(value) predicate and will return -1. See my comment below to do this in one line, with no extension method. Nov 4, 2011 at 0:07
  • var index = GridView1.DataKeys.OfType<DataKey>().Select((dk, i) => new { Index = i, Value = dk.Value }).Where(dk => dk.Value.Equals(value)).Select(dk => dk.Index).DefaultIfEmpty(-1).First(); Nov 4, 2011 at 0:20
  • @DylanVester You are incorrect. keys is a List not a DataKeyArray. It's not always better to write it in one line of code, even if you can.
    – Mark Good
    Dec 4, 2011 at 20:53
3

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()
0
3

Ok, most of those are wrong. Phil is the only one that works. The answer doesn't work. The problem with Phil's answer is that it's tied to a SQL DataTable in asp.net, which no one uses those. Well some do, but when you start using design patterns that gets dropped.

My example details iterating row by row and switching the pageindex and rebinding. I couldn't search the actual DataSource property because it is bound to a LinqDataSource control and I can't get to the actual data. And searching the DataSource would probably not work anyways because you have searching, sorting, etc to change the data around and grabbing it's actual row index won't be the grid's ( or other control's ) index.

I used a hidden asp:HiddenControl to keep the value because, a jQuery function actually executes the postback. grdLocations is the gridview

grdLocations.SelectedIndex = -1;

        bool found = false;
        int index = 0;
        int pageIndex = 0;
        for (int i = 0; i < grdLocations.PageCount; i++)
        {
            for (index = 0; index < grdLocations.DataKeys.Count; index++)
            {
                if (Convert.ToInt32(grdLocations.DataKeys[index].Value.ToString())  == Convert.ToInt32(hidCurrentRigId.Value))
                {
                    found = true;
                    break;
                }
            }

            if (found)
                    break;

            pageIndex++;
            grdLocations.PageIndex = pageIndex;
            grdLocations.DataBind();
        }

        if (found)
        {
            grdLocations.PageIndex = pageIndex;
            grdLocations.SelectedIndex = index;
        }

This will iterate each page in the grid view and select the correct data key.

Now to add if you want the easiest way to find a page based on row use this math in this sample console application. This keeps it really simple

    class Program
{
    static void Main(string[] args)
    {
        int rowIndex = 27;
        int pageCount = 7;
        int currentPage = 3;
        int pageSize = 10;

        Console.WriteLine("Page = " + (rowIndex / pageSize).ToString());
        Console.WriteLine("Row = " + ( rowIndex % pageSize).ToString());
        Console.ReadLine();
    }
}

Hope this helps someone.

2

Try this Linq approach:

grdMyGrid.SelectedIndex = grdMyGrid.DataKeys.OfType<DataKey>().ToList<DataKey>().FindIndex(dk => (string)dk.Value == "myKey");
2
//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;
   }
}
0

Put something like this in your GridView_RowDataBound() event:

Dim p As Catalog.Product = CType(e.Row.DataItem, Catalog.Product)
If p IsNot Nothing Then

    If p.Bvin = MySpecificID Then
        e.Row.RowState = DataControlRowState.Selected
    End If

End If

In this example, we are binding the GridView to a collection of custom objects of type Catalog.Product and the DataKey is named Bvin - you will need to adjust the datatype and key name depending on what you are binding to.

Note this event runs once per row already, so there is no need to loop. However, care should be taken to prevent things like data access from occurring more than once.

0

Basically, if you already have the instance of the GridViewRow, then do this:

gridView.SelectedIndex = gridViewRowToBeSelected.RowIndex;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.