简体   繁体   中英

Generating Drop Down list items from code behind using C#

i am trying to generate drop down list from code behind but i am getting this error:

Object reference not set to an instance of an object.
Line 101:        ddlGroupName1.DataSource = cmd.ExecuteReader();

can someone please help? here is my aspx code:

 <asp:DropDownList ID="ddlGroupName1" runat="server" OnSelectedIndexChanged="GroupNameChanged1"
                                        AutoPostBack="true" AppendDataBoundItems="true">
                                        <asp:ListItem Text="ALL" Value="ALL"></asp:ListItem>
                                        <asp:ListItem Text="Top 10" Value="10"></asp:ListItem>
                                    </asp:DropDownList>

here is my code behind

 private void GetGroupNameList(DropDownList ddlGroupName1)
    {
        DataSet dataSet = new DataSet();
        String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
        SqlConnection con = new SqlConnection(strConnString);

        SqlCommand cmd = new SqlCommand("select distinct GroupName" +
                        " from MyTable");
        cmd.Connection = con;
        con.Open();
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.Fill(dataSet);

        ddlGroupName1.DataSource = dataSet.Tables[0];

        ddlGroupName1.DataBind();
        con.Close();
        ddlGroupName1.Items.FindByValue(ViewState["MyFilter"].ToString())
                .Selected = true;
    }

ExecuteReader returns a datareader which requires you to iterate each row. You have a couple of options. Either iterate the datareader with:

    SqlDataReader reader = cmd.ExecuteReader();
    while (reader.Read())
    {
        // Add your values to a List of entities or DataTable, then bind to that
    }

Or use the SqlDataAdapter to dump it directly into a DataSet/DataTable and bind to that.

Like so:

DataSet dataSet = new DataSet();
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
   using (SqlCommand cmd = new SqlCommand("select distinct GroupName" +
                    " from MyTable"))
   {
       cmd.Connection = con;

       SqlDataAdapter da = new SqlDataAdapter(cmd);
       da.Fill(dataSet);

       ddlGroupName1.DataSource = dataSet.Tables[0];
       ddlGroupName1.DataBind();
   }
}

I don't think you can use .datasource = sqldatareader() You need to load the data into datatable and do .datasource = _dtDataTable. sqldatareader() is a real time one by one read row.

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