Skip to main content Skip to footer

Auto-size ComboBoxCellType Columns in Spread for WinForms

The AutoSize feature of TextCellType and GeneralCellType Columns in Spread for WinForms can be implemented using GetPreferredColumnWidth method of the SheetView class. This method basically gets the width of the widest text string in the specified column on the sheet. However, this feature is not available for the ComboBoxCellType columns. In this blog article, we will be discussing an easy and simple implementation of this AutoSize feature for the ComboBoxCellType columns.

The Implementation

All we need to do is programmatically get the text from the list of the ComboBox and use the MeasureString method of the Graphics object to determine the width of the longest text. Now, the Width of the column is set to the value returned by the MeasureString method plus the width of the dropdown arrow. This involves the following steps: 1. Calculating the Width of the longest text from the ComboBox list items.


float _fTotalWidth = 0;  
for (int \_iCount = 0; \_iCount < cmbCountry.Items.Count(); _iCount++)  
  {  
     if (\_fTotalWidth < this.CreateGraphics().MeasureString(cmbCountry.Items[\_iCount], new  Font("Microsoft Sans Serif", 8.25f)).Width)  
       {  
          \_fTotalWidth = this.CreateGraphics().MeasureString(cmbCountry.Items[\_iCount], new Font("Microsoft Sans Serif", 8.25f)).Width;  
       }  
  }  

2. Add the Width of the DropDown arrow button with the above calculated Width.


\_fTotalWidth = \_fTotalWidth + SystemInformation.VerticalScrollBarWidth;  

3. Set ComboBoxCellType Column's Width to the above calculated value.


fpSpread1.ActiveSheet.Columns[2].Width =_fTotalWidth;  

and, you are done !! :) AutoSize Download Sample- VB Download Sample- C#

MESCIUS inc.

comments powered by Disqus