所以,我有一个DataGridView使用BindingList作为数据源
DataGridView.DataSource = new BindingList{...}
哪里
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.
欢迎任何想法!
你尝试过ValueMember =""或ValueMember ="."?
真的很hacky,但你可以添加一个属性ColorName
本身?(也许是通过部分课程)
public ColorName Self {get {return this;}}
然后设置`ValueMember ="Self";'
除此之外,你可能需要一个 TypeConverter
另一个选项可能是覆盖ToString()
on ColorName
返回Name
,而没有值/显示成员?
(更新:不,不)
已检查,ToString()
似乎工作:
public override string ToString() { return Name; }
并且只是不设置DisplayMember
或 a ValueMember
.
Whad'ya知道 - "自我"技巧也有效......
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{ new Car { Color = colors[0]} }; form.Controls.Add(grid); Application.Run(form); } } }