Paul
Paul

Reputation: 5223

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 SqlDataSource(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...

Upvotes: 1

Views: 100

Answers (2)

theChrisKent
theChrisKent

Reputation: 15099

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();

Upvotes: 1

Ta01
Ta01

Reputation: 31610

You need to set the DataTextField and DataValueFields appropriately

try

ddl_names.DataTextField = "name";
ddl_names.DataValueField = "name";

before the databind

Upvotes: 3

Related Questions