2014-12-29 121 views
0

我有一个ASPX页面上有一个下拉菜单。从SQL Server数据库填充下拉列表

<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> 

我希望下拉列表中的选项可以从客户名称的数据库填充。

这里是我的数据库是什么样子

database

这里是我的代码背后

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(); 

} 

我以前用这个代码。所以我必须错过简单的东西,但我不确定它是什么。

编辑 我没有得到任何错误。代码编译。但下拉列表保持空白。

+0

以什么方式不起作用?当你调试时,它在哪里/如何失败? – David

+0

对不起。应该已经提供了。它不填充下拉列表。我没有得到任何错误。 – onTheInternet

+0

同一代码块中的“IsPostBack”和“SqlConnection”会伤害我的眼睛。 – granadaCoder

回答

4

那么,我想你忘记绑定你的下拉列表了;

customerSelect.DataBind(); 

并使用using statement处置你SqlCommandSqlConnectionSqlDataReader代替手动调用.Dispose()方法。

using(SqlConnection con = new SqlConnection(connString)) 
using(SqlCommand cmd = con.CreateCommand()) 
{ 
    ... 
    ... 
    using(SqlDataReader ddlValues = cmd.ExecuteReader()) 
    { 
     ... 
    } 
} 
+0

YEP!非常正确。谢谢!我会在9分钟内接受答复。 – onTheInternet