在輸入Combobox內的text的值後,點擊下拉按鈕,Combobox下拉框內的值的內容如果與text的值相同,則會加深顯示,底色爲藍色。有時候,Combobox下拉框內容的值沒有經過排序,在進行關聯顯示的時候,可能不會顯示到我們想要的準確的值。比如說,Combobox的下拉框的內容如下
TestTestTest
TestTest
Test
TestTestTestTestTest
如果,在Combobox中輸入Test,那麼點擊下拉框時,是“TestTestTest”這一欄加深顯示,而不是我們所要的“Test”。
對於這種情況,以及我們想要修改默認的加深顏色和字體,可以採用一下的方法:
private void Form0109_Load(object sender, EventArgs e)
{
DefineComboBox ac = new DefineComboBox();
ac.Location = new Point(100,30);
var test3 = new List<string>();
test3.Add("TestTestTest");
test3.Add("TestTestTestTestTest");
test3.Add("Test");
test3.Add("TestTest");
test3.Add("TestTestTestTestTestTestTestTestTestTestTestTestTestTestTest");
ac.DataSource = test3;
this.Controls.Add(ac);
}
class DefineComboBox : ComboBox
{
new public System.Windows.Forms.DrawMode DrawMode { get; set; }
public Color HighlightColor { get; set; }//define the highlight color
public DefineComboBox()
{
base.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed;
this.HighlightColor = Color.LightBlue;
this.DrawItem += new DrawItemEventHandler(DefineComboBox_DrawItem);
}
void DefineComboBox_DrawItem(object sender, DrawItemEventArgs e)
{
if (e.Index < 0)
return;
ComboBox combo = sender as ComboBox;
string combotext = combo.Text;
<span style="color:#ff0000;"><strong>int index = combo.FindStringExact(combotext);
//if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
if (e.Index == index)</strong></span>
e.Graphics.FillRectangle(new SolidBrush(HighlightColor),
e.Bounds);
else
e.Graphics.FillRectangle(new SolidBrush(combo.BackColor),
e.Bounds);
e.Graphics.DrawString(combo.Items[e.Index].ToString(), e.Font,
new SolidBrush(Color.Black),
new Point(e.Bounds.X, e.Bounds.Y));
e.DrawFocusRectangle();
}
}
——————————————————————————————————————————————————————————————————
歡迎大神光臨菜鳥博客,希望能得到各位大神在編碼方面的指引,同時歡迎與我一樣剛進入編程世界的朋友一起討論學習!相信前進的道路上,有你們,編程世界會更加精彩!