您需要告诉它哪些字段用作值和文本。
ddlList.DataSource = sqlTa;
ddlList.DataValueField = "ValueField";
ddlList.DataTextField = "TextField";
ddlList.DataBind();
而且您的 select 语句缺少一个“。它应该是:
"Select Item FROM Calendar Where UserD='Test'"
一个例子是:
正如 ryan 指出的那样,如果您要撤回一个领域,那么您可以这样做:
DataTable dtTable = new DataTable();
try
{
using (SqlConnection sqlConnection = new SqlConnection("Your connection"))
{
using (SqlCommand sqlCommand = new SqlCommand("Select Item FROM Calendar Where UserD='Test'", sqlConnection))
{
sqlConnection.Open();
using (SqlDataReader sqlDataReader = sqlCommand.ExecuteReader())
{
dtTable.Load(sqlDataReader);
sqlDataReader.Close();
}
}
}
}
catch (Exception error)
{
throw error;
}
ddlList.DataSource = dtTable;
ddlList.DataBind();
但是,如果您有多个字段,那么您可以这样做:
DataTable dtTable = new DataTable();
try
{
using (SqlConnection sqlConnection = new SqlConnection("Your connection"))
{
using (SqlCommand sqlCommand = new SqlCommand("Select Item, id FROM Calendar Where UserD='Test'", sqlConnection))
{
sqlConnection.Open();
using (SqlDataReader sqlDataReader = sqlCommand.ExecuteReader())
{
dtTable.Load(sqlDataReader);
sqlDataReader.Close();
}
}
}
}
catch (Exception error)
{
throw error;
}
ddlList.DataSource = dtTable;
ddlList.DataValueField = "id";
ddlList.DataTextField = "item";
ddlList.DataBind();