在winform編程中,combox是我們經常用到的控件,往往因為界面排版或者其它原因,comboBox的寬度受到限制,而下拉列表中的內容太長。如果按照combobox的默認設置 ,下拉列表和comboBox的寬度一樣,並不會跟隨內容的變化而變化,這就造成下拉列表中有些項的內容太長而不能全部顯示出來,就是下面這個樣子:
如果能夠讓下拉列表的寬度隨著內容的變化而變化,這個問題不就解決了。下面我們看看如何讓comboxBox的下拉列表寬度自適應內容的寬度:
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();
}
}
上面的方法,只要在我們向combox添加完所有項後,調用一下,就可以調整comboBox下拉列表的寬度了
private void button1_Click(object sender, EventArgs e)
...{
comboBox1.Items.Add("美國");
comboBox1.Items.Add("中華人民共和國");
comboBox1.Items.Add("新疆維吾爾族自治區");
AdjustComboBoxDropDownListWidth(comboBox1);
}
到這裡,問題並沒有完結,如果每次在我們向comboBox中添加一項後,就要調用一下這個方法,那就太麻煩了。能不能把這種自適應寬度的功能集成到comboBox中呢?可以,這裡我們繼承ComboBox,實現一個自定義的控件,在用戶每次打開下拉列表的時候,讓控件自動調整下拉列表的寬度。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using.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
&nbs + 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();
}
}
}
}