[英]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: 这是我的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>
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. ExecuteReader返回一个数据读取器,该数据读取器要求您迭代每一行。 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. 或者使用SqlDataAdapter将其直接转储到DataSet / DataTable中并绑定到该数据集。
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. 我认为您不能使用.datasource = sqldatareader()您需要将数据加载到datatable
并执行.datasource = _dtDataTable。 sqldatareader() is a real time one by one read row. sqldatareader()是实时的一对一读取行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.