Reputation: 7243
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
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
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