【问题标题】:Getting the items of a ComboBox with its DataSource filled获取填充了 DataSource 的 ComboBox 的项目
【发布时间】:2010-10-26 10:15:22
【问题描述】:

考虑有一个通过其 DataSource 属性填充的 ComboBox。 ComboBox 中的每一项都是一个自定义对象,ComboBox 设置有DisplayMemberValueMember

IList<CustomItem> aItems = new List<CustomItem>();
//CustomItem has Id and Value and is filled through its constructor
aItems.Add(1, "foo"); 
aItems.Add(2, "bar");

myComboBox.DataSource = aItems;

现在的问题是,我想将项目读取为将在 UI 中呈现的字符串。考虑到我不知道 ComboBox 中每个项目的类型(CustomItem 我不知道)

这可能吗?

【问题讨论】:

    标签: c# winforms .net-2.0 controls combobox


    【解决方案1】:

    绑定:

    ComboBox1.DataSource = aItems;
    ComboBox1.DisplayMember = "Value";
    

    获取物品:

    CustomItem ci = ComboBox1.SelectedValue as CustomItem;
    

    编辑:如果你想要得到的只是组合框所有显示值的列表

    List<String> displayedValues = new List<String>();
    foreach (CustomItem ci in comboBox1.Items)
        displayedValues.Add(ci.Value);
    

    【讨论】:

    • 它是关于项目而不是选定的。
    【解决方案2】:

    创建一个接口,比如ICustomFormatter,并让那些自定义对象实现它。

    interface ICustomFormatter
    {
       public string ToString();
    }
    

    然后调用ToString()方法。

    编辑:链接到Decorator 模式。

    【讨论】:

    • 这是唯一的方法吗??我无法修改 CustomObject 类。有没有其他办法???
    • Object 定义了一个 ToString() 方法。如果你想这样做,你只需覆盖它而不是实现一个新接口。
    • 听起来是一个更好的解决方案。我将尝试修改CustomItem,如果我没有权限,将继续使用'decorator'的东西
    【解决方案3】:

    虽然计算成本稍高,但反射可以做你想做的事:

    using System.Reflection;    
    private string GetPropertyFromObject(string propertyName, object obj)
        {
            PropertyInfo pi = obj.GetType().GetProperty(propertyName);
            if(pi != null)
            {
                object value = pi.GetValue(obj, null);
                if(value != null)
                {
                    return value.ToString();
                }
            }
            //return empty string, null, or throw error
            return string.Empty;
        }
    

    【讨论】:

      【解决方案4】:

      您应该能够通过反射获得 ValueMember 和 DisplayMember。但是询问组合框可能会更容易一些。以下将起作用,但也许你想用 SuspendUpdate 或其他东西包围它。

      string s = string.Empty;
      int n = comboBox1.Items.Count;
      
      for (int i = 0; i < n; i++)
      {
          comboBox1.SelectedIndex = i;
          s = s + ';' + comboBox1.Text; // not SelectedText;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-01-20
        • 2016-03-18
        • 1970-01-01
        • 1970-01-01
        • 2018-08-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多