Mathematics
Mathematics

Reputation: 7618

Drop Down List not getting populated

I have a c# code line as,

using (SqlDataSource sqlds = new SqlDataSource(ConnectionString(), SelectCommand()))
            {
                drop1.DataSource = sqlds;
                drop1.DataTextField = "UserName";
                drop1.DataBind();
            }

now it's not populating my dropdownlist,

<asp:DropDownList id="drop1" runat="server" />

so I want to check if sql is returning data or not

if i put line break, I am not sure how to find out if sql is returning data, I am using using select statement and connection string for gridview and it works but not with drop down list

Upvotes: 0

Views: 1393

Answers (3)

danywalls
danywalls

Reputation: 709

Be sure you have your sqlquery into select command then you need convert you sqldatasource select command into dataview.

 string query = "select yourfield from yourtable";

using (SqlDataSource sqlds = new SqlDataSource(conn.ConnectionString, query))
{
   System.Data.DataView dv = (System.Data.DataView)sqlds.Select(DataSourceSelectArguments.Empty);
        if (dv.Count > 0)
        {
            DropDownList1.DataSource = sqlds;
            DropDownList1.DataTextField = "yourfield";
            DropDownList1.DataBind();
        }
  }

Upvotes: 2

Manish Mishra
Manish Mishra

Reputation: 12375

your way of binding datasource to the dropdown is correct and same thing is working for me.

Possible errors can be

  • in the connectionString. Verify if it is correct.
  • in the Select Query. Verify if the SelectCommand() methods returns correct sql query.

use Selected event of the SqlDataSource to verify whether it returned any row i.e

   sqlds.Selected += new SqlDataSourceStatusEventHandler(sdl_Selected);

where sql_Selected is:

  void sdl_Selected(object sender, SqlDataSourceStatusEventArgs e)
  {
      var a = e.AffectedRows;
  }

as a Side note - make sure your select query doesn't contain any string concatenation prone to sql injection. i.e. SELECT UserName from [TableName] where certainCol ="+ variable.

Don't do it

provide a sql parameter instead, and add the SelectParameters to your SqlDataSource

Upvotes: 1

Andrew Carmichael
Andrew Carmichael

Reputation: 3113

You should be able to put a breakpoint on drop1.DataSource = sqlds; and then move your mouse over sqlds and it should show you how many rows are contained in the DataSource.

Upvotes: 1

Related Questions