0

I am using this query to populate a drop down list on my ASP.NET page:

using (CountriesRegionsDataContext db = new CountriesRegionsDataContext())
        {
            ddlCountry.Items.Clear();
            ddlCountry.DataSource = from c in db.CountryCodes orderby c.CountryName select c;
            ddlCountry.DataTextField = "CountryName";
            ddlCountry.DataValueField = "CountryCode1";
            ddlCountry.AppendDataBoundItems = true;
            ddlCountry.DataBind();
            ddlCountry.Items.Insert(0, new ListItem("- Select a country -", "0"));
        }

The data source is a simple SQL table which contains no duplicates. However when my page renders, the bound data is repeated twice in the drop down list control (a-za-z).

Does anyone have an idea as to what might be going on? Using distinct() doesn't seem to solve the problem (and there is no duplicate data in the table), and I tried adding ToList() to the end of my query and that doesn't seem to be fixing it either.

16
  • Check your DB table again. Commented Jun 21, 2013 at 18:48
  • Any chance that code is executing twice? What happens if you comment out the last line? Commented Jun 21, 2013 at 18:48
  • 3
    If you switch "AppendDataBindItems" to false, does the problem go away? Commented Jun 21, 2013 at 18:49
  • 5
    @ElGavilan what that means is that somewhere, later on in the page's lifecycle, something is calling ddlCountry.DataBind() again, which causes the control to add the contents of the data source to the list a second time. Commented Jun 21, 2013 at 18:56
  • 1
    So, if DataBind is being called later on... why not just let it happen? Set AppendDataBoundItems to true and remove the call to DataBind. (Also, figure out why DataBind is being called later. That doesn't sound like expected behavior to me.) Commented Jun 21, 2013 at 19:20

1 Answer 1

4

Shamelessly stealing Adam Maras comment and posting as an answer:

What that means is that somewhere, later on in the page's lifecycle, something is calling ddlCountry.DataBind() again, which causes the control to add the contents of the data source to the list a second time.

Sign up to request clarification or add additional context in comments.

1 Comment

You figured out the what, I figured out the why. Yay, teamwork!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.