views:

75

answers:

2

I'm having a datagridview with combobox column in it. This column is databound. I want to set the width of the dropdown list as per the largest item width in the list. For a normal combobox to achieve the same I've used a extension method which will set the width of the combo box by finding the largest width item in the list. This is done in the DropDown event of the combobox.

Now in DataGridView combobox column I want to achieve the same. How can I get the DropDown event in this case? Please let me if there is any other way to achieve the same?

A: 

You can try setting the AutoSizeMode of the column to AllCellsExceptHeader, or AllCells. You can also set the MinimumWidth of the column if auto-sizing it causes it to become too narrow.

adrift
@adrift: I've fixed column width. I want to set the width of the drop down list only. I hope your solution changes the width of the column.
JPReddy
A: 

After little bit of investigation, I've found the answer for this.

I'm setting the datasource to the combobox column of the datagridview. So, after setting the datasource I'm finding the width of the largest item in the datatable for the value which is set as DisplayMember of the column. I'm using the same logic mentioned in the link given above in my question, instead of doing at DropDown event, I'm doing it while setting the Datasource, which is onetime. In the link given above in my question was setting the width of the drop down list every time drop down list is shown. So, in a way my approach looks good.

Here, how I done this:

// 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();
JPReddy