Question

I tried to override the default behavior of datagridview combox box column to make it accept enum as int. In order to do that, I created CustomComboboxCell and CustomComboboxEditingControl as follow:

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);
    }
}

Then in my form, I create a datagridview with a combobox column to test this:

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};
    }
}

I thoug that everything look perfect, but when I run the form, it still give me System.ArgumentException: DataGridViewComboboxCell value is not valid.

Please take a look at my code and tell me what did I miss?

Was it helpful?

Solution

After struggled for a night, finally I end up fix it by an "ugly" workaround which I don't want to from the start. I just switch from using Dictionary<int, string> to Dictionary<TestEnum, string> as datasource

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top