Binding collection to DropDownList

Posts   
 
    
Frogbite
User
Posts: 4
Joined: 01-May-2008
# Posted on: 01-May-2008 16:32:53   

Hi,

Can someone tell me if there is an easier way too bind an collection to a dropdownlist instead of:

            CountryCollection countryCollection = CountryManager.GetAllCountries();
            ddlCountries.Items.Add(new ListItem("",""));
            if (countryCollection.Count >0)
            {
                foreach (CountryEntity countryEntity in countryCollection)
                {
                    ListItem listItem = new ListItem(countryEntity.Name, countryEntity.CountryId.ToString());
                    ddlCountries.Items.Add(listItem);
                }
            }

I was thinking something like:

CountryCollection countryCollection = CountryManager.GetAllCountries();
ddlCountries.DataSource = countryCollection;
            ddlCountries.DataValueField = "ID";
            ddlCountries.DataTextField = "Name";
            ddlCountries.DataBind();

but this does nog work..... cry

Walaa avatar
Walaa
Support Team
Posts: 14995
Joined: 21-Aug-2005
# Posted on: 01-May-2008 16:44:52   

What does "doesn't work" mean? Please specify more info, exception text stack trace if available.

Try the following:

CountryCollection countryCollection = CountryManager.GetAllCountries();
ddlCountries.DataSource = countryCollection.DefaultView;
ddlCountries.DataValueField = "Id"; // I bet it's "Id" not "ID" 
ddlCountries.DataTextField = "Name";
ddlCountries.DataBind();