2013-02-25 78 views
0

我正在從XML文檔中讀取一個設置,將其轉​​換爲字符串數組,然後遍歷每個字符串並將它們添加到DropDownList。 一切出現工作正常,直到我真的去看看DropDownList本身。不管我做什麼,DropDownList都是空的,即使當我通過我的代碼進行調試時,一切看起來都是完美的。 如果任何人可以略述爲什麼沒有顯示,儘管事實上從代碼的角度來看它正在人口稠密,我將不勝感激。DropDownList儘管顯示爲填充,但卻不顯示任何值

我的代碼可以發現如下(請注意,我也試圖通過數據填充綁定,但我仍然有同樣的問題。):

public class InstrumentDropDownList : DropDownList 
{ 
    public InstrumentDropDownList() 
    { 
     PopulateDropDown(); 
    } 

    public void PopulateDropDown() 
    { 
     string unsplitList = Fabric.SettingsProvider.ReadSetting<string>("Setting.Location"); 
     string[] instrumentList = unsplitList.Split(','); 

     DropDownList instrumentsDropDown = new DropDownList(); 

     if (instrumentList.Length > 0) 
     { 
      foreach (string instrument in instrumentList) 
      { 
       instrumentsDropDown.Items.Add(instrument); 
      } 
     } 
    } 
} 
+0

您可以將代碼添加到顯示上述代碼的_usage_的答案中嗎? – 2013-02-25 16:56:33

+2

您不需要檢查intrumentList的長度是否大於0.如果長度已爲零,則foreach不會讓您進入。 – 2013-02-25 17:08:50

回答

1

您正在創建一個新的DropDownList並向其添加項目。問題是,你沒有對你創建的新DropDownList做任何事情。您只是將這些項目添加到錯誤的列表中。

public void PopulateDropDown() 
    { 
     string unsplitList = Fabric.SettingsProvider.ReadSetting<string>("Setting.Location"); 
     string[] instrumentList = unsplitList.Split(','); 

     if (instrumentList.Length > 0) 
     { 
      foreach (string instrument in instrumentList) 
      { 
       this.Items.Add(instrument); 
      } 
     } 
    } 

作爲替代方案,您應該也可以做到這一點。您顯然想要進行更多的驗證,但這只是爲了表明您可以使用數據源/數據綁定

public void PopulateDropDown() 
{ 
    this.DataSource = fabric.SettingsProvider.ReadSetting<string>("Setting.Location").Split(','); 
    this.DataBind(); 
} 
0

您需要foreach語句後調用instrumentsDropDown.DataBind

0
public class InstrumentDropDownList : DropDownList 
{ 
    public InstrumentDropDownList() 
    { 
     PopulateDropDown(); 
    } 

    public void PopulateDropDown() 
    { 
     string unsplitList = Fabric.SettingsProvider.ReadSetting<string>("Setting.Location"); 
     string[] instrumentList = unsplitList.Split(','); 

     DropDownList instrumentsDropDown = new DropDownList(); 

     if (instrumentList.Length > 0) 
     { 
      foreach (string instrument in instrumentList) 
      { 
       instrumentsDropDown.Items.Add(instrument); 
      } 
      instrumentsDropDown.DataBind(); 
     } 
    } 
} 
1

爲什麼在從同一個類繼承時創建DropDownList的新實例?你不應該這樣做嗎? base.Items.Add()??