我试图覆盖 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);
}
}
然后在我的表单中,我创建了一个带有组合框列的 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.
请看看我的代码并告诉我我错过了什么?