Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adjusting ComboBox DropDown Width in C#

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.

like image 596
Jim Fell Avatar asked Oct 26 '25 22:10

Jim Fell


2 Answers

Ok, so .Anchor didn't work like I expected it to, so here's a completely new answer which does work, but I feel is kind of a hack, (but maybe it's a perfectly reasonable way to manage it):

int x = 10;           
comboBox1.Location = new Point(comboBox1.Location.X - x, comboBox1.Location.Y);
comboBox1.Width += x; 

This code pulls it back along the x-axis by 10 pixels, and then expands ComboBox1 by 10 pixels.

This works very smoothly for me. Does this work for you?

like image 91
Pretzel Avatar answered Oct 28 '25 13:10

Pretzel


I wrote up an article on CodeProject on how to hack the combo-box to give it a scroll bar to scroll horizontally. See here for the article.

like image 20
t0mm13b Avatar answered Oct 28 '25 13:10

t0mm13b



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!