How to select cascading DropDownList with SqlDataSource

前端 未结 2 1010
小蘑菇
小蘑菇 2020-12-11 10:15

I have the following in my data base -

breedId Species Breed
0       dog      Alsatian
1       dog      pitbull
2       dog      Shetland sheepdog
3              


        
相关标签:
2条回答
  • 2020-12-11 10:58

    You need to use ControlParameter in SelectParameters.

    Make sure that AutoPostBack="True" for DropDownListSpecies

    FYI: You have typo in Speecies

    enter image description here enter image description here

    <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>
    
    0 讨论(0)
  • 2020-12-11 10:58

    You are not filtering the data in the second drop down list, based on the selection made in the first drop down list (which is what you want).

        <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>
    

    Also, you need to add the AutoPostBack="True" property to each DropDownList, if you want the changes to be reflected as soon as you change the value of each DropDownList.

    0 讨论(0)
提交回复
热议问题