Adjusting ComboBox DropDown Width in C#

Posted by Jim Fell on Stack Overflow See other posts from Stack Overflow or by Jim Fell
Published on 2010-05-20T20:49:45Z Indexed on 2010/05/20 21:00 UTC
Read the original article Hit count: 371

Filed under:
|
|

Hello. I have this code that adjusts the width of a comboBox drop-down:

  private void comboBox_DropDown(object sender, EventArgs e)
  {
     ComboBox senderComboBox = (ComboBox)sender;
     int width = senderComboBox.DropDownWidth;
     Graphics g = senderComboBox.CreateGraphics();
     Font font = senderComboBox.Font;
     int vertScrollBarWidth =
         (senderComboBox.Items.Count > senderComboBox.MaxDropDownItems)
         ? SystemInformation.VerticalScrollBarWidth : 0;
     int newWidth;

     foreach (string s in ((ComboBox)sender).Items)
     {
        newWidth = (int)g.MeasureString(s, font).Width
            + vertScrollBarWidth;

        if (width < newWidth)
        {
           width = newWidth;
        }
     }

     senderComboBox.DropDownWidth = width;
  }

It works great, except it expands the width of the drop-down to the right, whereas I would prefer it to expand to the left because the comboBox is located on the right side of my form. Any thoughts or suggestions you may have would be appreciated. Thanks.

© Stack Overflow or respective owner

Related posts about c#

Related posts about combobox