我正在尝试从我的数据库中获取值以填充下拉列表。
我调试了以下函数,它显示了预期的结果,但只将最后一个存储在返回值中:
public static string GetAllPlacements(string placementLocation)
{
string returnVal = null;
using (SqlConnection sqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["websiteContent"].ConnectionString))
{
sqlCon.Open();
string SQL = "SELECT DISTINCT " + placementLocation + " FROM Placements";
using (var CMD = new SqlCommand(SQL, sqlCon))
{
using (var DR = CMD.ExecuteReader())
{
while (DR.Read())
{
returnVal = DR[selectField].ToString();
}
}
}
sqlCon.Close();
}
return returnVal;
}
E.g。有两个结果,伦敦和巴黎,但“returnVal”只存储巴黎。
我将此数据绑定到下拉列表:
private void refreshLocation()
{
ddlLocation.DataSource = Placements.GetAllPlacements("Placement_Location");
ddlLocation.DataBind();
ddlLocation.Items.Insert(0, new ListItem("-- Please Select --", "0"));
}
在下拉列表中,巴黎选项显示如下:
P
A
R
I
S
而不是:
London
Paris
任何帮助都将不胜感激。
答案 0 :(得分:1)
您必须更改GetAllPlacements以返回例如字符串列表:
public static List<string> GetAllPlacements(string placementLocation)
{
string returnVal = new List<string>;
using (SqlConnection sqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["websiteContent"].ConnectionString))
{
sqlCon.Open();
string SQL = "SELECT DISTINCT " + placementLocation + " FROM Placements";
using (var CMD = new SqlCommand(SQL, sqlCon))
{
using (var DR = CMD.ExecuteReader())
{
while (DR.Read())
{
returnVal.Add(DR[selectField].ToString());
}
}
}
sqlCon.Close();
}
return returnVal;
}