我想要类似于以下伪代码的东西:
myGridView.SelectedIndex = myGridView.DataKeys.IndexOf("mySpecificKey");
我做了一些Intellisense探索,但我还没有找到一个明显的方法来做到这一点.如果找不到DataKey,我想将SelectedIndex设置为-1.
我结束了
For n As Integer = 0 To myGridView.DataKeys.Count - 1 If myGridView.DataKeys(n).Value = myKeyObj Then myGridView.SelectedIndex = n End If Next
你考虑过Linq方法吗?
用法:
GridView1.SelectedIndex = GridView1.DataKeys.IndexOf(id);
码:
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().ToList(); var key = keys.SingleOrDefault(k => k.Value.Equals(value)); if (key == null) return -1; return keys.IndexOf(key); } }