Fill asp: dropdownlist - VS 2008

I have a form with two DDLs named

State and city

Condition:

<asp:UpdatePanel ID="States" runat="server" UpdateMode="Conditional">
        <Triggers>
            <asp:AsyncPostBackTrigger ControlID="States"EventName="SelectedIndexChanged" />
        </Triggers>
        <ContentTemplate>
            <asp:DropDownList ID="States" runat="server"
            AutoPostBack="True" DataSourceID="StatesObjectDataSource" 
            AppendDataBoundItems="true" 
                onselectedindexchanged="States_SelectedIndexChanged">
            <asp:ListItem Value="-1" Text="- None -"/>    
            </asp:DropDownList>
            <asp:ObjectDataSource ID="StatesObjectDataSource" runat="server" 
                onselecting="StatesObjectDataSource_Selecting" 
                SelectMethod="GetStates" 
                TypeName="Something">
            </asp:ObjectDataSource>
        </ContentTemplate>
    </asp:UpdatePanel>

      

Town:

<asp:DropDownList ID="Cities" runat="server">
        </asp:DropDownList>

      

When they select a state, I want to populate the DDL cities with all the cities for that state.

In the code behind, I can get to

States_SelectedIndexChanged(object sender, EventArgs e)

      

and I'm trying to fill DDL of the City with this

Cities.Items.Add(new ListItem(city,city));

      

However, I do not see that my DDL cities inhabited by

+1


source to share


3 answers


I recommend creating a private property in ViewState that contains a collection of physical objects. Then add an object to this list, then bind the list of objects to the dropdown list.

Page For

<asp:DropDownList runat="server" ID="ddlCity" DataValueField="Key" DataTextField="Value">
</asp:DropDownList>

      



Code for

private List<KeyValuePair<string, string>> ListData
{
    get { return (List<KeyValuePair<string, string>>) (ViewState["ListData"] ??     
                 (ViewState["ListData"] = new List<KeyValuePair<string, string>>())); }
    set { ViewState["ListData"] = value; }
}

protected void States_SelectedIndexChanged_SelectedIndexChanged(object sender, EventArgs e)
{
  ListData.Add(new KeyValuePair<string, string>(ddlCitys.SelectedValue, ddlCitys.SelectedValue));
  ddlCitys.DataSource = ListData;
  ddlCitys.DataBind();
}

      

The get statement also uses lazy loading on the ListData property, so when accessing the list you will never encounter an empty reference exception.

+2


source


If at all possible, I would suggest using the CascadingDropDown Extender instead of UpdatePanel. There is no need to reinvent this wheel and the Toolkit control uses web services instead of partial postbacks (much faster).



+1


source


Place your city DropDownList on the update bar.

+1


source







All Articles