我尝试覆盖datagridview combox box列的默认行为,使其接受枚举为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);
}
}
然后在我的表单中,我创建了一个带有组合框列的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.
请查看我的代码并告诉我我错过了什么?
答案 0 :(得分:0)
经过一夜的挣扎,最后我最终以一个丑陋的&#34;我从一开始就不想要的解决方法。我只是从使用Dictionary<int, string>
切换到Dictionary<TestEnum, string>
作为数据源