2010-02-05 68 views
0

我看过很多关于将字典绑定到下拉列表的文章,当值是一个字符串时。如何将字典<Int32,CustomClass>绑定到下拉列表

如果该值是一个具有该类别的特定属性的类别,那么它将显示在下拉菜单中,该怎么办?

Dictionary<Int32, MyClass> 

// Value 
class MyClass { 
    public String Yer="123"; 
    public String Ner="321"; 
} 

如何显示在我的下拉财产也门里亚尔一个绑定到该词典吗?

+0

你可以更具体 - WinForms,WebForms,或MVC? – 2010-02-05 09:41:12

+0

糟糕。对不起,我的意思是WebForms – 2010-02-05 09:43:35

+0

你想附加什么作为Value和Text? – 2010-02-05 09:50:58

回答

0

您需要使用DataTextFieldDataValueField属性组合。试试这个:

private void Page_Load(object sender, EventArgs e) 
    { 
     List<MyDummyObject> data = new List<MyDummyObject>() 
      { 
       new MyDummyObject() {ID = 1, RandomBoolValue = true, SomeRandomDescription = "First item" } 
       ,new MyDummyObject() {ID=2, RandomBoolValue = false, SomeRandomDescription = "Second item" } 
      }; 

     comboBox1.DataTextField = "SomeRandomDescription"; 
     comboBox1.DataValueField = "ID"; 
     comboBox1.DataSource = data; 
     comboBox1.DataBind(); 
    } 


    private class MyDummyObject 
    { 
     public int ID { get; set; } 
     public string SomeRandomDescription { get; set; } 
     public bool RandomBoolValue { get; set; } 

     public override string ToString() 
     { 
      return "zzzzzz"; 
     } 
    } 

上MyDummyObject的重写的ToString只是为了证明它不会被调用(这是默认的动作,如果你不指定DataTextFieldDataValueField)。

+0

这些属性在ASP.NET DropDownList上不存在 – 2010-02-05 10:02:14

+0

Ahh对不起,我确定您最初在上面的注释中使用了Winforms?没关系,我已经修改了我的答案。 – slugster 2010-02-05 10:08:45

相关问题