例如:需要Gridview選中“欄目名稱”為“辦事指南”的那行,注意DataKeyNames中必須有“欄目名稱”,否則将會出現錯誤!!不知道誰還有更好的方法解決這個問題,小女子在此熱盼高手指教:
<asp:GridView ID="GridView1" runat="server" DataSourceID="ObjectDataSource1" DataKeyNames="欄目編号,欄目名稱" BackColor="White" BorderColor="White" BorderStyle="Ridge" BorderWidth="2px" CellPadding="3" CellSpacing="1" GridLines="None">
<Columns>
<asp:CommandField ShowDeleteButton="True" ShowSelectButton="True" />
</Columns>
<FooterStyle BackColor="#C6C3C6" ForeColor="Black" />
<RowStyle BackColor="#DEDFDE" ForeColor="Black" />
<SelectedRowStyle BackColor="#9471DE" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#C6C3C6" ForeColor="Black" HorizontalAlign="Right" />
<HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#E7E7FF" />
</asp:GridView>
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim Row As GridViewRow
For Each Row In GridView1.Rows
'Dim KeyValue As String = GridView1.DataKeys(Row.RowIndex).Value 取得“欄目編号”列的值,Value也可以寫成Values(0) ,Values的索引是與Gridview中的DataKeyNames相對應的
Dim KeyValue As String = GridView1.DataKeys(Row.RowIndex).Values(1) '取得“欄目名稱”列的值
If (KeyValue = "辦事指南") Then
GridView1.SelectedIndex = Row.RowIndex
End If
Next
End Sub