SqlDataSource refusing to cooperate
I'm trying to populate a drop down list with data from an SQL database but I fail miserably. Code seems ok to me but refuses to work.
SqlDataSource sql_Names = new SqlData开发者_StackOverflow中文版Source(WebConfigurationManager.ConnectionStrings[1].ConnectionString, "SELECT name FROM Names");
sql_Names.DataSourceMode = SqlDataSourceMode.DataReader;
ddl_names.DataSource = sql_Names;
ddl_names.DataBind();
The database connection is working. It creates the right amount of entries (same as the number of rows in the DB) in the drop down list but insted of the values it fills every element of the list with "System.Data.DataRecordInternal" (or "System.Data.DataRowView" if the mode is set to DataSet).
Please help...
You need to set the DataTextField and DataValueFields appropriately
try
ddl_names.DataTextField = "name";
ddl_names.DataValueField = "name";
before the databind
you need to set the ddl_names.DataTextField and ddl_names.DataValueField properties. So your final code should look like this:
SqlDataSource sql_Names = new SqlDataSource(WebConfigurationManager.ConnectionStrings[1].ConnectionString, "SELECT name FROM Names");
sql_Names.DataSourceMode = SqlDataSourceMode.DataReader;
ddl_names.DataTextField = "name";
ddl_names.DataValueField = "name";
ddl_names.DataSource = sql_Names;
ddl_names.DataBind();
精彩评论