Mapping DatagridviewComboboxColumn Data to an Enumeration

I have a datagridview that is populated with receiving data from an SQL server.

gridview.Datasource = dataSet.Tables[0] 

-> There is no problem with this.

In this grid, one column is a ComboboxColumn ...

To populate (I mean, to bind only the data source) this, no problem:

cmb.DataSource = Enum.GetValues(typeof(MyEnum));
cmb.ValueType = typeof(MyEnum);
cmb.DataPropertyName = "MyEnum";

I would like to know how to bind data to datagridviewcomboboxcolumn (the value in the DB for this column is the index of the selected value for this combo box, and the data source of this combined code is Enum).

The value in DB: 2 →, which is the index of the item to display

Is it possible to clarify the DB column name somewhere? If I do this in datapropertyname, I get an error -> DataGridViewComboboxCell value is invalid ...

Thanks in advance!

edit: "". Enum datatable. .

+4
1

, :

, , , gridview, unbound comboboxColumn, , , datagridview , , CellEndEdit RowStateChanged:

 DataGridViewComboBoxColumn col = new DataGridViewComboBoxColumn();
 col.DataSource = Enum.GetValues(typeof(MyEnum));
 col.Name = "testcolumn";

 int index = dataGridView1.Columns.Add(col);
 //"index" is if you want to set properties and so on to this column
 //but no need for this example.
 //dataGridView1.Columns[index].Name = "testcolumn";

 dataGridView1.DataSource = test;

 //the 2 event-handlers         
 dataGridView1.CellEndEdit += new DataGridViewCellEventHandler(dataGridView1_CellEndEdit);
 dataGridView1.RowStateChanged += new DataGridViewRowStateChangedEventHandler(dataGridView1_RowStateChanged);

(CellEndEdit , , , , comboboxcell);

void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{   
      //here i use TestCol as a name for the column i want to check
      //you replace it with the column you have from the database
      //if you didnt change it of course...
      if (e.ColumnIndex == dataGridView1.Columns["TestCol"].Index)
      {
           //and here i assign the value on the current row in the testcolumn column
           //thats the combobox column...
           dataGridView1.Rows[e.RowIndex].Cells["testcolumn"].Value = (MyEnum)((int)dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value);
      }
}

private void dataGridView1_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e)
{
      //here i assign the initial values to the each cell in the combobox column
      //this whole example could be done in other ways but in a nutshell
      //it should provide you a good kickstart to play around.
      if (e.Row.DataBoundItem != null)
      {
           e.Row.Cells["testcolumn"].Value = (MyEnum)((int)e.Row.Cells["TestCol"].Value);
      }
}

, , 0 2 5, , , 5 , , :

public enum MyEnum
{
    zero,
    one,
    two,
    three,
    four,
    five
}
+2

All Articles