当我尝试数据dropdownlist
时,得到了这个:system.data.datarowview
我错了什么?
string strQuery = "Select Item FROM Calendar Where UserD="Test";
SqlConnection myConn;
SqlDataAdapter sqlDa = new SqlDataAdapter(strQuery,myConn);
DataTable sqlTa = new DataTable("Test");
da.Fill(sqlTa);
ddlList.DataSource = sqlTa;
ddlList.DataBind();
答案 0 :(得分:14)
string strQuery = "Select Item FROM Calendar Where UserD='Test'";
请注意,您需要在字符串周围使用单引号,因为在代码中您没有完成初始字符串,因此其余代码只是strQuery的一部分。
此外如果您将来带回多个字段,当您绑定下拉列表时,您需要指定数据库中的哪个字段是值,哪个是显示的文本。< / p>
ddlList.DataSource = sqlTa;
ddlList.DataValueField = "ValueFieldFromDatabaseResults";
ddlList.DataTextField = "ShownTextFieldFromDatabaseResults";
ddlList.DataBind();
答案 1 :(得分:2)
您需要告诉它使用哪些字段作为值和文本。
ddlList.DataSource = sqlTa;
ddlList.DataValueField = "ValueField";
ddlList.DataTextField = "TextField";
ddlList.DataBind();
你的select语句缺少一个“。应该是:
"Select Item FROM Calendar Where UserD='Test'"
示例是:
正如瑞安指出的那样,如果你要撤回一个领域,那么你可以这样做:
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();
答案 2 :(得分:1)
添加此行
ddlList.DataSource = sqlTa;
ddlList.DataValueField = "ValueFieldFromDatabaseResults";
ddlList.DataTextField = "ShownTextFieldFromDatabaseResults";
ddlList.DataBind();
然后你错过了
的连接字符串SqlConnection myConn="must add your connection string code here "
您尚未打开连接字符串
添加myconn.open()
的
SqlConnection myConn="must add your connection string code here "
`myconn.open()`
SqlDataAdapter sqlDa = new SqlDataAdapter(strQuery,myConn)
答案 3 :(得分:0)
试试这个..
ddlList.DataSource = sqlTa;
ddlList.DataTextField = "class";
ddlList.DataBind();
添加ddList.Value="somefield"
是可选的