Question

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

Was it helpful?

Solution

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

OTHER TIPS

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.

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top