我在互联网上找到了几个例子来做这个但是真的很难让它在VB中运行。 (试过一个转换器但结果好坏)
我需要根据第一个下拉列表中的不同值填充下拉列表的选项。
任何人都可以帮助VB中的一个简单的例子吗?如果值在脚本中被“硬编码”,则不会引起争议。或者从表中提取数据的SQL位
提前致谢!
答案 0 :(得分:2)
它的完成方式是在第一个下拉菜单的SelectedIndexChanged事件中填充第二个下拉列表
Protected Sub ddlCountry_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
Dim CountryID As Integer = Convert.ToInt32(ddlCountry.SelectedValue.ToString())
FillStates(CountryID)
End Sub
Private Sub FillStates(ByVal countryID As Integer)
Dim strConn As String = ConfigurationManager.ConnectionStrings("DatabaseConnectionString").ConnectionString
Dim con As New SqlConnection(strConn)
Dim cmd As New SqlCommand()
cmd.Connection = con
cmd.CommandType = CommandType.Text
cmd.CommandText = "Select StateID, State from State where CountryID =@CountryID"
cmd.Parameters.AddWithValue("@CountryID", countryID)
Dim objDs As New DataSet()
Dim dAdapter As New SqlDataAdapter()
dAdapter.SelectCommand = cmd
con.Open()
dAdapter.Fill(objDs)
con.Close()
If objDs.Tables(0).Rows.Count > 0 Then
ddlState.DataSource = objDs.Tables(0)
ddlState.DataTextField = "State"
ddlState.DataValueField = "StateID"
ddlState.DataBind()
ddlState.Items.Insert(0, "--Select--")
Else
lblMsg.Text = "No states found"
End If
End Sub
使用html源代码:
<asp:DropDownList ID="ddlState" runat="server" AutoPostBack="True">
</asp:DropDownList>
<asp:DropDownList ID="ddlCountry" runat="server"
AutoPostBack="True" OnSelectedIndexChanged="ddlCountry_SelectedIndexChanged">
</asp:DropDownList>
答案 1 :(得分:2)
您可以在ASPX页面中以声明方式完成此操作:
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:myConnString %>" SelectCommand="SELECT id, name FROM planets"></asp:SqlDataSource>
<asp:DropDownList ID="ddlPlanets" AutoPostBack="true" DataTextField="name" DataValueField="id" DataSourceID="SqlDataSource1" runat="server" AppendDataBoundItems="true" />
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:myConnString %>" SelectCommand="SELECT planetid, name FROM moons" FilterExpression="planetid = '{0}'">
<FilterParameters>
<asp:ControlParameter Name="planetid" ControlID="ddlPlanets" PropertyName="SelectedValue" />
</FilterParameters>
</asp:SqlDataSource>
<asp:DropDownList ID="ddlMoons" DataTextField="name" DataValueField="planetid" DataSourceID="SqlDataSource2" runat="server" />
答案 2 :(得分:0)
您最好的选择是在第一个下拉列表上捕获SelectedIndexChanged
事件,检查下拉列表的当前值是什么,然后使用清除然后填充第二个下拉列表中的项目。执行此操作时,请记住将第一个DropDownList的AutoPostBack
属性设置为"true"
。