Graphics g = null;
Font font = null;
try
{
int width = comboBox_jpgName.Width; //comboBox_jpgName是控件名字
font = comboBox_jpgName.Font;
g = comboBox_jpgName.CreateGraphics();
int vertScrollBarWidth = (comboBox_jpgName.Items.Count > comboBox_jpgName.MaxDropDownItems) ? SystemInformation.VerticalScrollBarWidth : 0;
int newWidth;
foreach (object s in comboBox_jpgName.Items)
{
if (s != null)
{
newWidth = (int)g.MeasureString(s.ToString().Trim(), font).Width
+ vertScrollBarWidth;
if (width < newWidth)
width = newWidth; //将下拉列表的宽度设置为最大项目的宽度。
if (comboBox_jpgName.Text.ToString().Equals(s.ToString()))
comboBox_jpgName.Width = newWidth+20;//当前选中为宽度为控件宽度
}
}
comboBox_jpgName.DropDownWidth = width;//将下拉列表的宽度设置为最大项目的宽度
}
catch
{ }
finally
{
if (g != null)
g.Dispose();
Font font = null;
try
{
int width = comboBox_jpgName.Width; //comboBox_jpgName是控件名字
font = comboBox_jpgName.Font;
g = comboBox_jpgName.CreateGraphics();
int vertScrollBarWidth = (comboBox_jpgName.Items.Count > comboBox_jpgName.MaxDropDownItems) ? SystemInformation.VerticalScrollBarWidth : 0;
int newWidth;
foreach (object s in comboBox_jpgName.Items)
{
if (s != null)
{
newWidth = (int)g.MeasureString(s.ToString().Trim(), font).Width
+ vertScrollBarWidth;
if (width < newWidth)
width = newWidth; //将下拉列表的宽度设置为最大项目的宽度。
if (comboBox_jpgName.Text.ToString().Equals(s.ToString()))
comboBox_jpgName.Width = newWidth+20;//当前选中为宽度为控件宽度
}
}
comboBox_jpgName.DropDownWidth = width;//将下拉列表的宽度设置为最大项目的宽度
}
catch
{ }
finally
{
if (g != null)
g.Dispose();
}
参考:http://blog.csdn.net/ccy3253/article/details/2067304