DataGridView,BindingList <t>,DataGridViewComboBoxColumn </t>

时间:2008-12-12 11:29:04

标签: .net winforms datagridview castle-activerecord

所以,我有一个DataGridView使用BindingList作为数据源

DataGridView.DataSource = new  BindingList<Car>{...}

其中

public class Car
{
    public ColorName Color { get; set;}
}

public class ColorName
{
    public int Id {get; set;}
    public string Name{get; set;}
}

我使用Combobox专栏:

DataGridViewComboBoxColumn colorNameDataGridViewTextBoxColumn;
colorNameDataGridViewTextBoxColumn.DataPropertyName = "Color";
colorNameDataGridViewTextBoxColumn.HeaderText = "Color";
colorNameDataGridViewTextBoxColumn.Name = "Color";
colorNameDataGridViewTextBoxColumn.DisplayMember = "Name";
colorNameDataGridViewTextBoxColumn.ValueMember = "Id";
colorNameDataGridViewTextBoxColumn.DataSource = new ColorName[] {...};

我怎样才能让它发挥作用?现在我得到一个例外,因为我认为它试图将Id转换为ColorName。

我尝试使用空的ValueMember或向ColorName类添加直接强制转换操作符但无法使其工作。

当然,我可以在Car类中使用int来表示颜色,但不是很好。

正如您可能猜到的那些类实际上是Castle Project ActiveRecord-s。

欢迎任何想法!

1 个答案:

答案 0 :(得分:5)

您是否尝试过ValueMember =“”或ValueMember =“。”?

真的很hacky,但你可以在ColorName上添加一个属性本身吗? (也许通过部分课程)

public ColorName Self {get {return this;}}

然后设置`ValueMember =“Self”;'

除此之外,您可能需要TypeConverter

另一个选项可能是覆盖ToString()上的ColorName以返回Name,而没有值/显示成员?


(更新:不,不)

检查过,ToString()似乎有效:

public override string ToString() { return Name; }

并且不要将DisplayMember 设为ValueMember


好吧,你知道 - “自我”的伎俩也有用......

using System;
using System.ComponentModel;
using System.Windows.Forms;
class ColorName
{
    public ColorName(int id, string name) {
        this.Id = id;
        this.Name = name;
    }
    public int Id { get; private set; }
    public string Name { get; private set; }

    // maybe declare this one in a partial class...
    public ColorName Self { get { return this; } }
}
class Car
{
    public ColorName Color { get; set; }
}

static class Program
{
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        using(Form form = new Form())
        using (DataGridView grid = new DataGridView())
        {
            grid.Dock = DockStyle.Fill;
            grid.AutoGenerateColumns = false;
            ColorName[] colors = new[] {
              new ColorName(1,"Red"),
              new ColorName(2,"Blue"),
              new ColorName(3,"Green")
            };
            var col = new DataGridViewComboBoxColumn
            {
                DataPropertyName = "Color",
                HeaderText = "Color",
                Name = "Color",
                DisplayMember = "Name",
                ValueMember = "Self",
                DataSource = colors
            };

            grid.Columns.Add(col);
            grid.DataSource = new BindingList<Car> {
                new Car { Color = colors[0]}
            };
            form.Controls.Add(grid);
            Application.Run(form);
        }
    }
}
豫ICP备18024241号-1