【发布时间】:2014-12-03 20:53:43
【问题描述】:
您好,我正在尝试让 DropDownList 与 SqlDataReader 一起使用,但它不填充 DropDownlist。 TextBox.Text 阅读器正在工作。
这是我正在使用的代码:
using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString))
{
SqlCommand command =
new SqlCommand("SELECT * FROM [datarep].[dbo].[OrderHeader] WHERE [OrderNumber] = '"+OrderNumber+"'", con);
con.Open();
SqlDataReader read = command.ExecuteReader();
while (read.Read())
{
TextBox2.Text = (read["CreatedDate"].ToString());
TextBox3.Text = (read["CreatedBy"].ToString());
CompanyStored = (read["CustomerID"].ToString());
TextBox7.Text = (read["Store_Number"].ToString());
DropDownList1.DataTextField = (read["Year"].ToString());
DropDownList1.DataBind();
}
read.Close();
}
【问题讨论】:
-
有多少项目被添加到
DropDownList..? also move yourDropDownList1.DataBind();` 在 While 循环之外并查找如何分配DataSource to the DropdownList -
仅添加 1 项 @DJKRAZE
-
好吧,如果碰巧有更多,我仍然会移动它,也看看这个MDSN Binding Data to DropDownList
-
谢谢@DJKRAZE
-
由于您只希望返回一条记录,因此您应该删除
while- 这使得您看起来可能有多个记录,这看起来会令人困惑。如果您确定您会获得一条记录,请执行read.Read();。如果你不确定,你可以if (read.Read())。无论哪种方式都清楚地表明您只需填写一次控件。