【问题标题】:Display List contents specific field in a ComboBox (C#)在组合框中显示列表内容特定字段(C#)
【发布时间】:2009-08-30 17:19:43
【问题描述】:

嗯,我的问题有点傻,但我尝试了很多不同的东西,但没有结果。

我的主窗体中有一个 ComboBox,我想将其数据源指向在 Filters 类中声明的公共只读 List PriceChanges 列表。没问题,但我想列出描述字段。

我尝试将“描述”字符串分配给 DisplayMember 属性,但没有成功。我的 ComboBox 仅列出:每个条目的“BusinessLogic.PriceChange”,其中 BusinessLogic 是我的命名空间的名称,PriceChange 是类。

感谢您的帮助。

问候

这是我的主窗体代码的一部分

    public mainFrm()
    {
        InitializeComponent();

        prodFilter = new Filters();
        cbPriceChanges.DataSource = prodFilter.PriceChanges;
        cbPriceChanges.DisplayMember = "Description"
    }

这是声明 List 对象的代码的一部分

public enum PriceChangeTypes
{
    No_Change,
    Increased,
    Decreased,
    All
}

public class PriceChange
{
    public String Description;
    public readonly PriceChangeTypes Type;

    public delegate bool ComparisonFuntionDelegate(Decimal a);
    public readonly ComparisonFuntionDelegate ComparisonFunction;

    public PriceChange(String Description, PriceChangeTypes type , ComparisonFuntionDelegate CompFunc)
    {
        this.Description = Description;
        Type = type;
        ComparisonFunction = CompFunc;
    }
}

public class Filters
{

    public readonly List<PriceChange> PriceChanges = null;

    public Filters()
    {
        PriceChanges = new List<PriceChange>();

        PriceChanges.Add(new PriceChange("No Change", PriceChangeTypes.No_Change, PriceChange => PriceChange == 0));
        PriceChanges.Add(new PriceChange("Increased", PriceChangeTypes.Increased, PriceChange => PriceChange > 0));
        PriceChanges.Add(new PriceChange("Decreased", PriceChangeTypes.Decreased, PriceChange => PriceChange < 0));
        PriceChanges.Add(new PriceChange("All", PriceChangeTypes.All, a => true));
    }
}

【问题讨论】:

  • Description、Type、ComparisonFuntionDelegate 和 ComparisonFunction 应该是私有的或者做成属性。

标签: c# user-interface list combobox


【解决方案1】:

您是否尝试过将“描述”设为属性?如果列表试图通过反射获取字段,它将发生很大变化(很可能是这样做的)。

public class PriceChange {
    public string Description{
        get;
        set;
    }
    // ...
}

【讨论】:

  • 完美,就是这样,我想我需要深入了解这个东西在内部的行为方式。干杯队友
【解决方案2】:

尝试将此添加到您的课程中:

public override string ToString()
        {
            return Description;
        }

目前您只是获取 ToString 的默认值,即对象命名空间和类

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 2021-12-25
    • 1970-01-01
    • 2013-12-21
    • 1970-01-01
    • 2016-08-31
    相关资源
    最近更新 更多