When I try to databing dropdownlist
, got this: system.data.datarowview
what do I wrong?
string strQuery = \"Select Item FROM
Try this..
ddlList.DataSource = sqlTa;
ddlList.DataTextField = "class";
ddlList.DataBind();
adding ddList.Value="somefield"
is optional
You need to tell it what fields to use as value and text.
ddlList.DataSource = sqlTa;
ddlList.DataValueField = "ValueField";
ddlList.DataTextField = "TextField";
ddlList.DataBind();
And your select statement is missing a ". It should be:
"Select Item FROM Calendar Where UserD='Test'"
An Example being:
As ryan pointed out if you are pulling back one field then you can just do:
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();
But if you have more then one field then you can do this:
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();
add this line way
ddlList.DataSource = sqlTa;
ddlList.DataValueField = "ValueFieldFromDatabaseResults";
ddlList.DataTextField = "ShownTextFieldFromDatabaseResults";
ddlList.DataBind();
then u miss connection string for
SqlConnection myConn="must add your connection string code here "
You have not open connection string so
add myconn.open()
for
SqlConnection myConn="must add your connection string code here "
`myconn.open()`
SqlDataAdapter sqlDa = new SqlDataAdapter(strQuery,myConn)
string strQuery = "Select Item FROM Calendar Where UserD='Test'";
Note you need to use single quotations around the string, as in your code you didn't finish the inital string ever, so the rest of the code just became part of strQuery.
In addition if you bring back more than one field in the future, when you bind a dropdown list you need to specify which field from the database is the value and which is the displayed text.
ddlList.DataSource = sqlTa;
ddlList.DataValueField = "ValueFieldFromDatabaseResults";
ddlList.DataTextField = "ShownTextFieldFromDatabaseResults";
ddlList.DataBind();