Link to home
Create AccountLog in
Avatar of JT_SIRO
JT_SIRO

asked on

How do I pre-populate a drop down and it's sub drop down?

I have a Category and Sub-Category dropdown in my asp.net app.  The Sub-Category is pulled from a database filtered by what was selected in the Category dd.  It populates from an update panel.  This works fine on a clean page, but I need to load a record and set the Category and Sub-Category according to what was stored in the DB.  I tried this, and only the Category gets set properly - but then the Sub-Category binds instead of taking on the DB value.  

Page_Load()
                    ddCategory.SelectedValue = dr["Category"].ToString();
                    ddSubCategory.SelectedValue = dr["SubCategory"].ToString();

I think I understand what's happening - this code fires before the SubCategory binds.  But how do I get around that?  My aspx code below

<!-- CATEGORY / SUBCATEGORY -->
        <div class="field" style="text-align:left;"><label for="fname">Category / Genre: </label> 
            <asp:DropDownList ID="ddCategory" runat="server" AutoPostBack="true"
                            DataSourceID="dsCategories" DataValueField="Category" ValidationGroup="MetaForm" 
                            DataTextField="Category" AppendDataBoundItems="true">
                <asp:ListItem></asp:ListItem>
            </asp:DropDownList>
        </div>    

        <!-- SUBCATEGORY UPDATE PANEL -->
        <asp:UpdatePanel ID="UpdatePanel2" runat="server">                        
        <ContentTemplate>
        <div class="field" style="text-align:left;"><label for="fname">Sub Category: </label> 
            <asp:DropDownList ID="ddSubCategory" runat="server" DataSourceID="dsSubCategories" 
                DataTextField="SubCategory">
                <asp:ListItem></asp:ListItem>
            </asp:DropDownList>
        </div>                  
            <asp:SqlDataSource ID="dsSubCategories" runat="server" ConnectionString="<%$ ConnectionStrings:SmashHausConnectionString %>"                                    
                               SelectCommand="SELECT [SubCategory] FROM [Categories] WHERE ([Category] = @Category) order by SubCategory asc">
                <SelectParameters>
                    <asp:ControlParameter ControlID="ddCategory" Name="Category" PropertyName="Text" Type="String" />
                </SelectParameters>
            </asp:SqlDataSource>
            </ContentTemplate>   
        </asp:UpdatePanel>

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of guru_sami
guru_sami
Flag of United States of America image

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account