数据绑定下拉列表
当我尝试数据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();
string strQuery = "Select Item FROM Calendar Where UserD='Test'";
请注意,您需要在字符串周围使用单引号,因为您的代码中没有完成初始字符串,因此其余代码只是strQuery的一部分。
此外, 如果您将来带回多个字段 ,当您绑定下拉列表时,您需要指定数据库中的哪个字段是值,哪个是显示的文本。
ddlList.DataSource = sqlTa; ddlList.DataValueField = "ValueFieldFromDatabaseResults"; ddlList.DataTextField = "ShownTextFieldFromDatabaseResults"; ddlList.DataBind();
您需要告诉它使用哪些字段作为值和文本。
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();
添加这一行方式
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)
试试这个..
ddlList.DataSource = sqlTa; ddlList.DataTextField = "class"; ddlList.DataBind();
添加ddList.Value="somefield"
是可选的