我试图覆盖datagridview组合框列的默认行为,使其接受enum作为int。为了做到这一点,我创建了CustomComboboxCell
和CustomComboboxEditingControl
,如下所示:
public class CustomComboboxEditingControl : DataGridViewComboboxEditingControl
{
public override object EditingControlFormattedValue
{
get
{
return base.EditingControlFormmatedValue;
}
set
{
if(value.GetType().IsEnum)
{
//convert enum to int
base.EditingControlFormattedValue = (int)value;
}
else
{
base.EditingControlFormattedValue = value;
}
}
}
}
public class CustomComboboxCell : DatagridviewComboboxCell
{
public override Type EditType
{
return typeof(CustomComboboxEditingControl);
}
}
然后在我的表单中,我创建了一个带有combobox列的datagridview来测试这个:
public enum TestEnum
{
a = 1,
b = 2,
c = 3,
}
public class Test
{
public TestEnum test {get;set;}
}
public class Form1
{
public Form1
{
Datagridview dgv = new Datagridview();
dgv.AutoGenerateColumns = false;
DatagridviewComboboxColumn col1 = new DatagridviewComboboxColumn();
col1.CellTemplate = new CustomComboboxCell();
//set datasource for col1
Dictionary<int, string> dct = new Dictionary<int, string>();
dct.Add(1, "a");
dct.Add(2, "b");
dct.Add(3, "c");
col1.Datasource = new BindingSource() {Datasource = dct};
col1.ValueMember = "key";
col1.DisplayMember = "value";
col1.DataPropertyName = "test";
dgv.Columns.Add(col1);
dgv.Invaidate();
this.Constrols.Add(dgv);
//Add datasource for datagridview
List<Test> lst = new List<Test>();
lst.Add(new Test() {test = TestEnum.a});
lst.Add(new Test() {test = TestEnum.b});
lst.Add(new Test() {test = TestEnum.c});
dgv.Datasource = new BindingList() {Datasource = lst};
}
}
我以为一切看起来都很完美,但当我运行表单时,它仍然会给我System.ArgumentException: DataGridViewComboboxCell value is not valid.
请看一下我的代码,告诉我我错过了什么?
在挣扎了一晚之后,我最终用了一个"丑陋"的变通方法来解决它,而我从一开始就不想这样做。我只是从使用Dictionary<int, string>
切换到使用Dictionary<TestEnum, string>
作为数据源