【问题标题】:C#: Binding hashtable to combo box questionC#:将哈希表绑定到组合框问题
【发布时间】:2009-10-21 14:57:33
【问题描述】:
    public class FontType
    {
        ...
        public String Name { get { return _name; } }
        public String DisplayName { get { return _displayName; } }
        public Font UseFont { get { return _font; } }
    }


bindFontTypes.DataSource = availableFonts;
comboFontType.DataSource = bindFontTypes;
comboFontType.ValueMember = "Key";
comboFontType.DisplayMember = ...???;

这里,bindFontTypes 是 BindingSource。 availableFonts 是一个哈希表,其中键是字符串,值是 FontType 的对象。对于comboFontType.DisplayMember,我想使用对象的 .DisplayName 属性。我该如何指定?有可能吗?

【问题讨论】:

    标签: c# winforms data-binding combobox hashtable


    【解决方案1】:

    如果你设置它可能会起作用

    comboFontType.DisplayMember = "Value";  // FontType
    

    并为FontType 重载ToString()

    作为 ToString() 的替代方法,您可以处理组合框的 Format 事件。

    但我什至不确定数据绑定是否以这种方式工作。

    【讨论】:

      【解决方案2】:

      通过使用DisplayMember = "Value.DisplayName",我正在将最后一个添加到哈希表中...我正在努力将它们全部...

      这就是我所做的......但只获取 Hashtable 中的最后一项来绑定......

      BindingSource src = new BindingSource();
                  src.DataSource = new Hashtable 
                  { 
                  {
                      "blah", 
                      new FontType 
                      { 
                          Name = "newFont", 
                          DisplayName = "new Font" 
                      } 
                      },
                      { 
                          "another", 
                          new FontType 
                          {
                              Name = "anotherFont",
                              DisplayName = "another Font" 
                          } 
                          } 
                  };
                  comboBox1.DataSource = src;
                  comboBox1.ValueMember = "Key";
                  comboBox1.DisplayMember = "Value.DisplayName";
      

      【讨论】:

      • 这在某处给了我“对象引用未设置为对象的实例”。它不是独立的程序,调试起来很痛苦。另一个解决方案有效。不过谢谢你的回复。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-18
      • 1970-01-01
      相关资源
      最近更新 更多