2011-03-25 174 views
2

我绑定字典的下拉列表中。绑定下拉列表与字典

说,例如我在字典中的下列项目:

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

我想下拉文本采取以下格式:

Test1 - Count: 123 
Test2 - Count: 321 

我正沿着以下路径会没有运气:

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

谢谢:)

回答

5

你可以通过在你的字典使用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(); 
1

我不认为DropDownList的不支持DataTextFormatString就像你想这样做是Concat的字符串。据我所知,你只能使用格式字符串的数字和日期。 (例如,请参阅此处:http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listcontrol.datatextformatstring.aspx

您可以按照ChristiaanV建议的方式(匿名类型)或使用您自己的POCO class(仅包含属性的类)执行此操作。
注意,使用匿名类型的范围有限。你不能usem他们在一个BusinessLayer组装并具有GUI的大会使用的结果,因为从方法返回匿名类型的能力是非常有限的。

我建议你做这样的事情:

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分配给DropDownL的DataSourceID IST。
1

不能使用的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())); 
     }