我的数据库中有以下内容 -
breedId Species Breed
0 dog Alsatian
1 dog pitbull
2 dog Shetland sheepdog
3 dog Boxer
4 cat Dragon Li
5 cat Australian Mist
6 cat Korat
在c#设计师视图中,我有2个下拉列表,其中有物种和其他品种。
当用户在物种列表中选择“狗”时,我想要的是,
品种列表应具有以下Alsatian, pitbull, Shetland sheepdog,Boxer
当我选择'dog'时,会显示数据库中的所有品种。
<asp:DropDownList ID="DropDownListSpecies" runat="server"
Height="27px" Width="107px" DataSourceID="hs330"
DataTextField="Species" DataValueField="Species">
</asp:DropDownList>
<asp:SqlDataSource ID="Species" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT DISTINCT [Species] FROM [Breed]">
</asp:SqlDataSource>
<asp:DropDownList ID="DropDownListBreed" runat="server" Height="20px"
Width="110px" DataSourceID="breed" DataTextField="Breed"
DataValueField="Breed">
</asp:DropDownList>
<asp:SqlDataSource ID="breed" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT DISTINCT [Breed] FROM [Breed]">
</asp:SqlDataSource>
答案 0 :(得分:3)
您需要在 SelectParameters 中使用 ControlParameter 。
确保 DropDownListSpecies
AutoPostBack =“True”仅供参考: Speecies
<asp:DropDownList ID="DropDownListSpecies" runat="server"
Height="27px" Width="107px" DataSourceID="Species"
DataTextField="Species" DataValueField="Species" AutoPostBack="True">
</asp:DropDownList>
<asp:SqlDataSource ID="Species" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT DISTINCT [Species] FROM [Breed]"></asp:SqlDataSource>
<asp:DropDownList ID="DropDownListBreed" runat="server"
Height="20px" Width="110px"
DataSourceID="breed" DataTextField="Breed" DataValueField="Breed">
</asp:DropDownList>
<asp:SqlDataSource ID="breed" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT DISTINCT [Breed] FROM [Breed] WHERE Species=@Species">
<SelectParameters>
<asp:ControlParameter ControlID="DropDownListSpecies" PropertyName="SelectedValue"
Name="Species " Type="String" DefaultValue="cat" />
</SelectParameters>
</asp:SqlDataSource>
答案 1 :(得分:1)
您没有根据第一个下拉列表中的选择(这是您想要的)过滤第二个下拉列表中的数据。
<asp:DropDownList ID="DropDownListBreed" runat="server" Height="20px" Width="110px" DataSourceID="breed" DataTextField="Breed" DataValueField="Breed">
</asp:DropDownList>
<asp:SqlDataSource ID="breed" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT DISTINCT [Breed] FROM [Breed] WHERE Species = @Species">
<SelectParameters>
<asp:ControlParameter ControlID="DropDownListSpecies" PropertyName="SelectedValue"
Name="Species " Type="String" DefaultValue="cat" />
</SelectParameters>
</asp:SqlDataSource>
此外,如果您希望在更改每个DropDownList的值后立即反映更改,则需要将 AutoPostBack =“True”属性添加到每个DropDownList。