private void AdjustComboBoxDropDownListWidth(object comboBox)
...{
Graphics g = null;
Font font = null;
try
...{
ComboBox senderComboBox = null;
if (comboBox is ComboBox)
senderComboBox = (ComboBox)comboBox;
else if (comboBox is ToolStripComboBox)
senderComboBox = ((ToolStripComboBox)comboBox).ComboBox;
else
return;
int width = senderComboBox.Width;
g = senderComboBox.CreateGraphics();
font = senderComboBox.Font;
//checks if a scrollbar will be displayed.
//If yes, then get its width to adjust the size of the drop down list.
int vertScrollBarWidth =
(senderComboBox.Items.Count > senderComboBox.MaxDropDownItems)
? SystemInformation.VerticalScrollBarWidth : 0;
int newWidth;
foreach (object s in senderComboBox.Items) //Loop through list items and check size of each items.
...{
if (s != null)
...{
newWidth = (int)g.MeasureString(s.ToString().Trim(), font).Width
+ vertScrollBarWidth;
if (width < newWidth)
width = newWidth; //set the width of the drop down list to the width of the largest item.
}
}
senderComboBox.DropDownWidth = width;
}
catch
...{ }
finally
...{
if (g != null)
g.Dispose();
}
}
private void button1_Click(object sender, EventArgs e)
...{
comboBox1.Items.Add("美国");
comboBox1.Items.Add("中华人民共和国");
comboBox1.Items.Add("新疆维吾尔族自治区");
AdjustComboBoxDropDownListWidth(comboBox1);
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
namespace WindowsApplication2
...{
class MyComboBox : ComboBox
...{
protected override void OnDropDown(EventArgs e)
...{
base.OnDropDown(e);
AdjustComboBoxDropDownListWidth(); //调整comboBox的下拉列表的大小
}
private void AdjustComboBoxDropDownListWidth()
...{
Graphics g = null;
Font font = null;
try
...{
int width = this.Width;
g = this.CreateGraphics();
font = this.Font;
//checks if a scrollbar will be displayed.
//If yes, then get its width to adjust the size of the drop down list.
int vertScrollBarWidth =
(this.Items.Count > this.MaxDropDownItems)
? SystemInformation.VerticalScrollBarWidth : 0;
int newWidth;
foreach (object s in this.Items) //Loop through list items and check size of each items.
...{
if (s != null)
...{
newWidth = (int)g.MeasureString(s.ToString().Trim(), font).Width
+ vertScrollBarWidth;
if (width < newWidth)
width = newWidth; //set the width of the drop down list to the width of the largest item.
}
}
this.DropDownWidth = width;
}
catch
...{ }
finally
...{
if (g != null)
g.Dispose();
}
}
}
}