[asp.net]如何在grid裡面產生"選取",選取之後還可以回到後端取得該筆資料的細節(DataKeyNames,DataKeys,SelectedIndexChanged)

  • 3292
  • 0
  • 2012-06-01

摘要:[asp.net]如何在grid裡面產生"選取",選取之後還可以回到後端取得該筆資料的細節

當然要先設定aspx的gridview拉,我是覺得用畫面拉一拉比較快拉

<asp:GridView ID="dtGrid" runat="server" AutoGenerateColumns="False" 
                DataSourceID="SqlDataSource1" DataKeyNames="EmployeeID,FirstName,LastName"   >
                <Columns>
                    <asp:CommandField ButtonType=Link HeaderText="選擇標的" SelectText="選我" ShowHeader="True" 
                        ShowSelectButton="True" />
                    <asp:BoundField DataField="EmployeeID" HeaderText="EmployeeID" />
                    <asp:BoundField datafield="FirstName" HeaderText="FirstName" />
                    <asp:BoundField datafield="LastName" HeaderText="LastName" />                    
                </Columns>
                <SelectedRowStyle ForeColor="Red" />
            </asp:GridView>

然後當然要設定grid的SelectedIndexChanged事件囉,當然在UI畫面那邊設定grid的屬性SelectedIndexChanged會比較快:

Protected Sub dtGrid_SelectedIndexChanged(sender As Object, e As EventArgs) Handles dtGrid.SelectedIndexChanged


    End Sub

加入以下程式碼即可讀取你選取的那行資料囉

Dim empid As String = dtGrid.DataKeys(dtGrid.SelectedIndex)("EmployeeID")
        Dim lastName As String = dtGrid.DataKeys(dtGrid.SelectedIndex)("LastName")