0

我正在尝试从我的数据库中获取值以填充下拉列表。

我已经调试了以下函数,它带来了预期的结果,但只将最后一个存储在返回值中:

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

例如,有两个结果,伦敦和巴黎,但“returnVal”只存储巴黎。

我将此数据绑定到下拉列表:

private void refreshLocation()
{
    ddlLocation.DataSource = Placements.GetAllPlacements("Placement_Location");
    ddlLocation.DataBind();

    ddlLocation.Items.Insert(0, new ListItem("-- Please Select --", "0"));
}

在下拉列表中,选项 Paris 如下所示:

P
A
R
I
S

而不是这个:

London
Paris

任何帮助,将不胜感激。

4

1 回答 1

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;
    }
于 2013-04-06T22:26:05.840 回答