onTheInternet
onTheInternet

Reputation: 7243

Populate drop down list from SQL Server database

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.

Upvotes: 0

Views: 2773

Answers (1)

Soner G&#246;n&#252;l
Soner G&#246;n&#252;l

Reputation: 98740

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())
    {
       ...
    }
}

Upvotes: 4

Related Questions