Generating Drop Down list items from code behind using C#

moe picture moe · Mar 29, 2013 · Viewed 7.4k times · Source

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

Answer

Adam Plocher picture Adam Plocher · Mar 29, 2013

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