Search code examples
winformsc#-4.0datagridviewcolumndatagridviewcombobox

DataGridViewComboBoxColumn Autosizes Incorrectly or Correctly-Only-on-Selection


I have a DataGridViewComboBoxColumn object which serves as a datasource for one of the columns in my gridview.

The code is as follows:

DataGridViewComboBoxColumn comboBoxColumn = new DataGridViewComboBoxColumn();

comboBoxColumn.DataSource = Enum.GetValues(typeof(MyEnums));
comboBoxColumn.DataPropertyName = "MyPropertyName";
comboBoxColumn.Name = "My Column Name";

dataGridView.Columns["MyPropertyName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
//dataGridView.Columns["MyPropertyName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
//dataGridView.Columns["MyPropertyName"].Width = CalculateColumnWidthFromEnum(typeof(MyEnums));
dataGridView.Columns.Remove(dataGridView.Columns["MyPropertyName"]);
dataGridView.Columns.Insert(1, comboBoxColumn);

I am happy with how WinForms displays my enums appropriately and whatnot. However, the words describing my enums will be cut short and only expand if I open the drop down and then leave that control.

I also tried manually setting the width (as shown by the commented-out lines) and that had no effect

I have two columns like this in my grid view.

Am I missing something here?


Solution

  • I had the approach all wrong.

    I was adjusting the width of a column I removed

    dataGridView.Columns.Remove(dataGridView.Columns["MyPropertyName"]);
    

    Instead I should have set the column width using the comboBoxColumn as such:

    comboBoxColumn.Width = whateverWidthIwant;
    

    Thanks for everyone's help!