Adjusting ComboBox DropDown Width in C#
I have this code that adjusts the width of a comboBox drop-down:
privat开发者_开发问答e 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.
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?
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.
You might want to look at placing the control within a container. For instance, create a FlowLayoutPanel with its FlowDirection property to RightToLeft. Place the ComboBox within the new panel. One benefit of this method is you may change the dimensions by any means and the control/container will behave as expected.
After much searching, it appears that this is actually along-standing problem that Microsoft has yet to address (big surprise). I've decided to re-arrange my layout to better-accomodate this feature-lack when I get the time, but for now, I'm just going to live with it. Thanks, everyone, for your input.
精彩评论