简体   繁体   中英

Binding Drop Down List from Code behind using C#

I am trying to bind drop-down box from code behind, but I am getting a compilation error:

'System.Web.UI.WebControls.SqlDataSource' does not contain a definition for 'DataSource'

I have tried to figure out but cannot seem to fix this issue.

<asp:DropDownList ID="MYDDL" Width="300px" DataTextField="PRJ_TITLE" AutoPostBack="true"
                  DataValueField="PRJ_ID" runat="server">
</asp:DropDownList> 

Here is my function:

private void Bind_DD()
{
    String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["myCon"].ConnectionString;
    SqlConnection con2 = new SqlConnection(strConnString);
    SqlDataAdapter sda = new SqlDataAdapter();
    SqlCommand cmd1 = new SqlCommand("SELECT  ID, PRJ_TITLE FROM myTable");

    cmd1.Connection = con2;
    con2.Open();

    myDDL.DataSource = cmd1.ExecuteReader();
    myDDL.DataTextField = "PRJ_TITLE";
    myDDL.DataValueField = "ID";
    myDDL.DataBind();

    con2.Close();

}

So it looks like you are possibily a bit mixed up about sql data connections as there are many ways to do them. I elected to do a databing via the sqlDataAdapter to DataTable.

Additionally make sure you do not have any elements in your markup that have a asp:SqlDataSource anywhere in your markup.

private void Bind_DD()
{
    DataTable dt = new DataTable();

    using(SqlConnection con2 = new SqlConnection(ConfigurationManager.ConnectionStrings["myCon"].ConnectionString))
    {
        con2.Open();

        SqlCommand cmd1 = new SqlCommand("SELECT  ID, PRJ_TITLE FROM myTable",con2);
        SqlDataAdapter sda = new SqlDataAdapter(cmd1);
        sda.Fill(dt);
    }

    myDDL.DataSource = dt;
    myDDL.DataTextField = "PRJ_TITLE";
    myDDL.DataValueField = "ID";
    myDDL.DataBind();

}

Try this:

private void Bind_DD()
{
    String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["myCon"].ConnectionString;
    SqlConnection con2 = new SqlConnection(strConnString);

    DataSet ds = new DataSet();
    SqlCommand cmd1 = new SqlCommand("SELECT  ID, PRJ_TITLE FROM myTable");
    cmd1.Connection = con2;
    con2.Open();
    SqlDataAdapter sda = new SqlDataAdapter(cmd1);
    sda.Fill(ds);
    myDDL.DataSource = ds; //cmd1.ExecuteReader();
    myDDL.DataTextField = "PRJ_TITLE";
    myDDL.DataValueField = "ID";
    myDDL.DataBind();
    con2.Close();
    //myDDL.DataBind(); 
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM