簡體   English   中英

將下拉列表與字典綁定

[英]Bind drop down list with Dictionary

我將字典綁定到下拉列表。

舉例來說,我在字典中有以下項目:

{"Test1", 123}, {"Test2", 321} 

我希望下拉文本采用以下格式:

Test1 - Count: 123
Test2 - Count: 321

我沒有走運就走以下道路:

MyDropDown.DataTextFormatString = string.Format("{0} - Count: {1}", Key, Value);

謝謝 :)

您可以通過在字典上使用LINQ來創建投影視圖,並創建一個匿名類型來保存您的自定義格式。

Dictionary<string, int> values = new Dictionary<string, int>();
values.Add("First", 321);
values.Add("Second", 456);
values.Add("Third", 908);


var displayView = from display in values
                    select new { DisplayText = display.Key + " Count: " + display.Value };

DropDownList1.DataSource = displayView;
DropDownList1.DataTextField = "DisplayText";
DropDownList1.DataBind();

我不認為DropDownList確實支持DataTextFormatString ,它可以像您想要的那樣連接字符串。 據我所知,您只能將格式字符串用於數字和日期。 (有關示例,請參見此處: http : //msdn.microsoft.com/zh-cn/library/system.web.ui.webcontrols.listcontrol.datatextformatstring.aspx

您可以按照ChristiaanV提出的方式(匿名類型)進行操作,也可以使用自己的POCO class (僅包含屬性的類)。
請注意,使用匿名類型具有有限的范圍。 您不能在BusinessLayer-Assembly中使用它們,而讓GUI-Assembly使用結果,因為從方法返回匿名類型的能力非常有限。

我建議你做這樣的事情:

public class MyPOCO
{
  public int MyPrimaryKey {get;set;}
  public String DisplayString {get;set;}
}

在您的代碼中創建一個List<MyPOCO>並將其綁定到DataSource屬性。 DataValueField設置為MyPrimaryKey,將DataTextField為DisplayString

如果您對回發的數據綁定有疑問,可以執行以下操作:

  1. 創建一個返回List<MyPOCO>
  2. 創建一個ObjectDataSource並使用向導選擇您在1中創建的方法。
  3. 將ObjectDataSource的ID分配給DropDownList的DataSourceID

您不能在其中使用string.Format

DataTextFormatString

請嘗試以下代碼。

Dictionary<string, int> s = new Dictionary<string, int>();
        s.Add("Test1", 123);
        s.Add("Test2", 321);

        foreach(KeyValuePair<string,int> temp in s)
        {
            DropDownList1.Items.Add(new ListItem(string.Format("{0} - Count: {1}", temp.Key, temp.Value),temp.Value.ToString()));
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM