Search code examples
c#datagridviewdatagridviewcombobox

combobox inside a datagridview with bound data


I've created a Datagridview that is bound to a Class CTag. Inside CTAG I have 2 members that I want to show in the datagridview : name, area The columns are created automatically because the class CTag is connected as datasource to the Datagridview. But I want to limit wat the user enters inside the "area" column. So in that place I want to have a combobox. I already found out how to add a new combobox with a list of options in the datagridview, but it creates an extra column this way.

private BindingList<string> listOfAreas         = new BindingList<string>();

listOfAreas.Add("PE");
listOfAreas.Add("PA");
listOfAreas.Add("MK");
listOfAreas.Add("DB");
listOfAreas.Add("CT");
listOfAreas.Add("TM");

dgvTags.DataSource = listOfTags;

DataGridViewComboBoxColumn area = new DataGridViewComboBoxColumn();
area.Name = "DataArea";
area.DataPropertyName = "DataArea";
area.DataSource = listOfAreas;
dgvTags.Columns.Add(area);

What am I missing to get this correct?


Solution

  • Move this line:

    dgvTags.DataSource = listOfTags;
    

    After this:

    dgvTags.Columns.Add(area);
    

    Explanation:

    When the AutoGenerateColumns property is true (default), when you set the DataSource, columns are created for each property of the type of the list if there is no column for that property.

    Therefore, if you add the column before placing it in DataSource, you will avoid a double column.