我使用以下代码填充我的DropDownList;
while (myDataReader.Read())
{
DropDownList1.Items.Add(myDataReader[0].ToString());
DropDownList1.DataValueField = myDataReader[1].ToString();
DropDownList1.DataTextField = myDataReader[0].ToString();
}
但无论DropDownList1中选择了什么,DataValue始终是从while循环读取的最后一个DataValue。
我做错了什么?
答案 0 :(得分:0)
我没有使用myDataReader,而是将dropdownList绑定到数据源
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString);
SqlCommand cmd = new SqlCommand("Select * from students", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
DropDownList1.DataTextField = ds.Tables[0].Columns["FullName"].ToString();
DropDownList1.DataValueField = ds.Tables[0].Columns["id"].ToString();
DropDownList1.DataSource = ds.Tables[0];
DropDownList1.DataBind();
答案 1 :(得分:-1)
因此,您似乎希望将数据库列名称用作数据值字段。但实际上,您实际上是将列值(而不是列名称)作为数据值字段提供。您的代码应如下所示:
DropDownList1.DataValueField = "ValueColumn"; //name of the value column, such as 'id' from the database
DropDownList1.DataTextField = "NameColumn"; //name of the descriptive column, such as 'name'
while (myDataReader.Read())
{
//also, we removed the 'ToString' because we want to provide the datarow object, not the converted string value
DropDownList1.Items.Add(myDataReader[0]);
}