Setting DropDown List Width for DataGridView ComboBoxColumn - WinForms

I have a datagridview with a combobox column. This column contains data. I want to set the width of the drop-down list according to the largest width of the item in the list. For a normal combobox to achieve the same, I used an extension method that sets the width of the combo box by finding the largest width element in the list. This is done in the DropDown event in the combo box.

Now in the combobox column of the DataGridView I want to achieve the same. How can I get a DropDown event in this case? Please allow me if there is another way to achieve the same?

+3
source share
2 answers

After a little investigation, I found the answer for this.

I am setting a data source in a combobox column in a datagridview. So, after setting the data source, I find the width of the largest element in the datatable for the value that is set as the DisplayMember column. I use the same logic that was mentioned in the link above in my question, instead of doing it in a DropDown event, I do this by setting the data source that was at the same time. In the link above, in my question, the width of the drop-down list was indicated for each drop-down list. So my approach looks good.

Here is how I did it:

// This line is picked up from designer file for reference
  DataGridViewComboBoxColumn CustomerColumn; 

  DataTable _customersDataTable = GetCustomers();

  CustomerColumn.DataSource = _customersDataTable;
  CustomerColumn.DisplayMember = Customer_Name;
  CustomerColumn.ValueMember = ID;

  var graphics = CreateGraphics();

  // Set width of the drop down list based on the largest item in the list
  CustomerColumn.DropDownWidth = (from width in
                         (from DataRow item in _customersDataTable.Rows
                          select Convert.ToInt32(graphics.MeasureString(item[Customer_Name].ToString(), Font).Width))
                       select width).Max();
+4
source

AutoSizeMode AllCellsExceptHeader AllCells. MinimumWidth , .

+1

Source: https://habr.com/ru/post/1768963/


All Articles