2013-04-06 131 views
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")); 
} 

在下拉列表中選擇巴黎出現這樣的:

P 
A 
R 
I 
S 

取而代之的是:

London 
Paris 

任何幫助,將不勝感激。

+0

什麼是'selectField'價值? – 2013-04-06 22:28:45

回答

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