// 動態改變顯示的長度
private void Form1_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("myID");
dt.Columns.Add("myValue");
dt.Rows.Add(new object[] { "1", "Bermuda 百慕達" });
dt.Rows.Add(new object[] { "2", "Bosnia and Herzegovina 波希尼亞及赫塞哥維那" });
cbxExamination.DataSource = dt;
cbxExamination.DisplayMember = "myValue";
cbxExamination.ValueMember = "myID";
// 在資料繫結後加入以下語法
SetDropDownWidth(comboCountry);
}
/// <summary>
/// 設定下拉選單下拉後的長度為最長內容的長度
/// </summary>
/// <param name="myCombo"></param>
/// <returns></returns>
private void SetDropDownWidth(ComboBox myCombo)
{
int maxSize = 0;
System.Drawing.Graphics g = CreateGraphics();
for (int i = 0; i < myCombo.Items.Count; i++)
{
myCombo.SelectedIndex = i;
SizeF size = g.MeasureString(myCombo.Text, myCombo.Font);
if (maxSize < (int)size.Width)
{
maxSize = (int)size.Width;
}
}
myCombo.DropDownWidth = myCombo.Width;
if (myCombo.DropDownWidth < maxSize)
{
myCombo.DropDownWidth = maxSize;
}
}
結果如下

沒有留言:
張貼留言