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.
SelectedValue Property (System.
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;
}
}
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
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With