我正在尝试从后面的代码生成下拉列表,但出现此错误:
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;
}