0

I have an ASPX page that has a drop down on it.

<div>
    <p>Pick a customer to show their order(s)</p>
    <asp:DropDownList ID="customerSelect" AutoPostBack="true" runat="server" OnSelectedIndexChanged="customerSelect_SelectedIndexChanged"></asp:DropDownList>
</div>

I want the options in the drop down to be populated from a database of customer names.

Here is what my database looks like

database

Here is my code behind

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        populateDropDown();
        customerSelect_SelectedIndexChanged(null, null);
    }
}

public void populateDropDown()
{
    SqlCommand cmd = new SqlCommand("SELECT * FROM [Orders]", new SqlConnection(ConfigurationManager.AppSettings["ConnString"]));
    cmd.Connection.Open();

    SqlDataReader ddlValues;
    ddlValues = cmd.ExecuteReader();

    customerSelect.DataSource = ddlValues;
    customerSelect.DataValueField = "OrderID";
    customerSelect.DataTextField = "CustomerName";

    cmd.Connection.Close();
    cmd.Connection.Dispose();

}

I've used this code before. So I must be missing something simple but I'm not sure what it is.

EDIT I am getting no errors. The code compiles. But the drop down list remains blank.

5
  • In what way is this not working? When you debug this, where/how does it fail? Commented Dec 29, 2014 at 13:34
  • I'm sorry. Should have provided that. It does not populate the drop down list. I get no errors. Commented Dec 29, 2014 at 13:35
  • "IsPostBack" and "SqlConnection" in the same code block hurts my eyes. Commented Dec 29, 2014 at 14:13
  • @granadaCoder why is that? Can you explain? I'm new to this so any advice is appreciated. Commented Dec 29, 2014 at 15:01
  • "Separation of Concerns" is the concept. weblogs.asp.net/arturtrosin/… Commented Dec 29, 2014 at 15:31

1 Answer 1

4

Well, I think you forget to bind your dropdownlist like;

customerSelect.DataBind();

And use using statement to dispose your SqlCommand, SqlConnection and SqlDataReader instead of calling .Dispose() method manually.

using(SqlConnection con = new SqlConnection(connString))
using(SqlCommand cmd = con.CreateCommand())
{
    ...
    ...
    using(SqlDataReader ddlValues = cmd.ExecuteReader())
    {
       ...
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

YEP! Exactly right. Thank you! I will accept answer in 9 minutes.

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.