我在DataGridView中遇到ComboBoxColumn问题。我使用自己的类型列表填充ComboBoxColumn的DataSource,并相应地设置DataPropertyName
,DisplayMember
和ValueMember
。
问题是:当我选择不同的值并选择另一个单元格时,我得到一个异常,因为long类型的值无法转换回对象。
用于DropDown值的类:
public class Unit
{
public long? ID { get; set;}
public string Name { get; set;}
public Unit(long id, string name)
{
ID = id;
Name = name;
}
}
用于DataGridView数据的类:
public class Data
{
public long? Amount { get; set; }
public Unit ChosenUnit { get; set; }
public Data(long? amount, Unit unit)
{
Amount = amount;
ChosenUnit = unit;
}
}
我正在填写DropDown和Grid这样的
List<Unit> units = new List<Unit>();
units.Add(new Unit(1, "grams"));
units.Add(new Unit(2, "kilograms"));
units.Add(new Unit(3, "tons"));
List<Data> data = new List<Data>();
data.Add(new Data(200, units[0]));
data.Add(new Data(2, units[1]));
data.Add(new Data(1, units[2]));
gridData.AutoGenerateColumns = false;
gridData.Columns.Add("Amount", "Amount");
gridData.Columns["Amount"].DataPropertyName = "Amount";
DataGridViewComboBoxColumn cboColUnits = new DataGridViewComboBoxColumn();
cboColUnits.Items.AddRange(units.ToArray());
cboColUnits.HeaderText = "Unit";
cboColUnits.DataPropertyName = "ChosenUnit";
cboColUnits.DisplayMember = "Name";
cboColUnits.ValueMember = "ID";
cboColUnits.ValueType = typeof(long?);
gridData.Columns.Add(cboColUnits);
gridData.DataSource = data;
将数据填充到网格视图中工作正常,但是当我选择不同的单位时,我得到以下异常:
我该怎么做才能解决这个问题?我是否需要实现某些事件处理程序或创建自定义编辑控件?
答案 0 :(得分:1)
将属性添加到Unit
类作为自引用 - 提示:也覆盖Equals
方法。然后将该新属性设置为ValueMember
:
public class Unit
{
public long? ID { get; set; }
public string Name { get; set; }
public Unit Self { get { return this; } }
public Unit(long id, string name)
{
ID = id;
Name = name;
}
public override bool Equals(object obj)
{
if (obj != null && obj is Unit)
{
if ((obj as Unit).ID == this.ID && (obj as Unit).Name == this.Name) //* See Footnote
{
return true;
}
}
return base.Equals(obj);
}
}
*在你的Equals
被覆盖的方法中,不要忘记考虑你的可空类型检查,我为了简洁而没有编码 - 但你明白了。
DataGridViewComboBoxColumn cboColUnits = new DataGridViewComboBoxColumn();
cboColUnits.Items.AddRange(units.ToArray());
cboColUnits.HeaderText = "Unit";
cboColUnits.DataPropertyName = "ChosenUnit";
cboColUnits.DisplayMember = "Name";
cboColUnits.ValueMember = "Self";
cboColUnits.ValueType = typeof(Unit);