有幾個部分的回答你的問題,我做了一些假設(你使用Visual Studio作爲IDE,你可以使用VB作爲你的後臺代碼語言):
我要綁定一個SQL語句來填充下拉列表...
你可以做到這一點無論是在代碼隱藏或通過Visual Studio的GUI。雖然您可以爲下拉列表使用綁定字段,但templatefield最終會爲您提供更多靈活性。我讀了templatefield(here),因爲它將成爲你的朋友,使用Gridview查看超出基本數據顯示的任何內容。使用GUI,選擇下拉列表應該給你一個右上角的小箭頭,它允許你創建一個數據連接和數據源來綁定你的下拉列表。
還可根據用戶使用此下拉列表作出選擇,我 要填充下一列(列2)與相應的數據
這是一個有點複雜,因爲你需要在下拉列表上觸發PostBack(使用AutoPostBack),處理Dropdownlist的SelectedIndexChanged事件,在第二列中找到要更新的控件,並根據Dropdownlist中的selectedindex/item /值更新該控件。有幾種方法可以做到這一點,但這裏是我找到的最快(使用asp.net winforms)。我正在使用SQL Adventureworks數據庫,使用employeeID填充第1列中的templatefield中的下拉列表,並使用選定的employeeID使用該employeeID的managerID填充第2列中的標籤。
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1"
EnableModelValidation="True" AutoGenerateColumns="False"
DataKeyNames="EmployeeID">
<Columns>
<asp:BoundField DataField="EmployeeID" HeaderText="EmployeeID"
InsertVisible="False" ReadOnly="True" SortExpression="EmployeeID" />
<asp:TemplateField>
<ItemTemplate>
Select EmployeeID
<asp:DropDownList ID="ddEmpID" runat="server" OnSelectedIndexChanged="ddEmpID_SelectedIndexChanged"
DataSourceID="SqlDataSource1" DataTextField="EmployeeID"
DataValueField="EmployeeID" AutoPostBack="True">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="labManagerID" runat="server" Text="ManagerID"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="Data Source=MyServer\Instance;Initial Catalog=AdventureWorks;Integrated Security=True"
ProviderName="System.Data.SqlClient"
SelectCommand="SELECT TOP(10) EmployeeID, ManagerID FROM HumanResources.Employee">
</asp:SqlDataSource>
而且從代碼隱藏SelectedIndexChanged事件:
Protected Sub ddEmpID_SelectedIndexChanged(sender As Object, e As EventArgs)
Dim myDDList As DropDownList = CType(sender, DropDownList)
Dim gvRow As GridViewRow = CType(myDDList.NamingContainer, GridViewRow)
Dim myLabel As Label = CType(gvRow.FindControl("labManagerID"), Label)
' Create your sql query here to populate a data object and assign values throughout your row
Dim myConnection As SqlConnection = New SqlConnection("Data Source=MyServer\Instance;Initial Catalog=AdventureWorks;Integrated Security=True")
Dim myCmd As SqlCommand = New SqlCommand("Select ManagerID FROM HumanResources.Employee WHERE EmployeeID='" + myDDList.SelectedValue + "'", myConnection)
If myConnection.State = ConnectionState.Closed Then myConnection.Open()
myLabel.Text = myCmd.ExecuteScalar
If myConnection.State = ConnectionState.Open Then myConnection.Close()
End Sub
而且,由於與GridView的工作有時是自虐的練習,我建議你有一些好的walkthrough tutorials在眼前:
-J