1

我正在尝试从后面的代码生成下拉列表,但出现此错误:

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

有人可以帮忙吗?这是我的 aspx 代码:

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

这是我背后的代码

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

2 回答 2

5

ExecuteReader 返回一个数据读取器,它要求您迭代每一行。你有几个选择。使用以下方法迭代数据读取器:

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

或者使用 SqlDataAdapter 将其直接转储到 DataSet/DataTable 并绑定到它。

像这样:

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();
   }
}
于 2013-03-29T18:51:47.210 回答
1

我认为您不能使用 .datasource = sqldatareader() 您需要将数据加载到datatable并执行 .datasource = _dtDataTable。sqldatareader() 是实时的一一读取行。

于 2013-03-29T18:51:03.843 回答