0

Can anyone help me with a C# loop to populate an ASP:DropDownList. I am using the following code to bind the data to my dropdown. However, the first result doesn't populate in the drop down list. There should be 3 however, there is only 2 in the dropdown list.

Any help is great.

        SqlDataReader dr;
        dr = sqlcmd.ExecuteReader();
        dropdown.DataSource = dr;

        while (dr.Read())
        {
            dropdown.DataValueField = "ID";
            dropdown.DataTextField = "Description";
            dropdown.DataBind();
        }

2 Answers 2

1

Since you're binding the data reader to the drop down, you don't need to loop at it explicitly (the call to dr.Read() is effectively eating the first element).

Try this:

SqlDataReader dr = sqlcmd.ExecuteReader();
dropdown.DataSource = dr;
dropdown.DataValueField = "ID";
dropdown.DataTextField = "Description";
dropdown.DataBind();

UPDATE

To add a default item, do this after the code above:

dropdown.Items.Insert(0, new ListItem("Please Select",""));
Sign up to request clarification or add additional context in comments.

2 Comments

is there a way to have a "Please Select" option on the drop down. It is being overwritten by the databind.
@claw: added that to the answer
1

Instead of

dropdown.DataValueField = "ID";
dropdown.DataTextField = "Description";

use

dropdown.DataValueField = dr["ID"].ToString();
dropdown.DataTextField = dr["Description"].ToString();

Comments

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.