Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set selected row in ASP.NET GridView based on DataKey?

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.

like image 289
Larsenal Avatar asked Dec 08 '08 18:12

Larsenal


People also ask

What property shows you the field that will be used for the selected value for a gridview?

SelectedValue Property (System.


3 Answers

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;
            }
        }
like image 54
tkaragiris Avatar answered Oct 12 '22 23:10

tkaragiris


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
like image 21
Larsenal Avatar answered Oct 12 '22 23:10

Larsenal


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);
    }
}
like image 5
Mark Good Avatar answered Oct 13 '22 00:10

Mark Good