2014-05-13 56 views
0

我想知道是否可以创建组合框(下拉列表)并在下拉列表中绘制特定的单元格。 所以,如果我有五个项目在下拉列表中,第二个项目和最后一个项目将被绘成蓝色,例如灰色的其他。 是否有可能?组合框 - 下拉列表

System.Windows.Forms.ComboBox comboBox; 
comboBox = new System.Windows.Forms.ComboBox(); 
comboBox.AllowDrop = true; 
comboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; 
comboBox.FormattingEnabled = true; 
comboBox.Items.AddRange(excel.getPlanNames()); 
comboBox.Location = new System.Drawing.Point(x, y); 
comboBox.Name = "comboBox1"; 
comboBox.Size = new System.Drawing.Size(sizeX, sizeY); 
comboBox.TabIndex = 0; 
group.Controls.Add(comboBox); 

感谢的任何帮助..

+1

[Microsoft在MSDN帮助中提供了一个示例](http://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.drawitem%28v=vs.110%29.aspx) –

回答

2

可以使用DrawItem事件。

首先你要设置的DrawModeComboBoxOwnerDrawFixed

然后,设置DrawItem为类似以下内容:

private void comboBox1_DrawItem(object sender, DrawItemEventArgs e) 
{ 
    Font font = (sender as ComboBox).Font; 
    Brush backgroundColor; 
    Brush textColor; 

    if (e.Index == 1 || e.Index == 3) 
    { 
     if ((e.State & DrawItemState.Selected) == DrawItemState.Selected) 
     { 
      backgroundColor = Brushes.Red; 
      textColor = Brushes.Black; 
     } 
     else 
     { 
      backgroundColor = Brushes.Green; 
      textColor = Brushes.Black; 
     } 
    } 
    else 
    { 
     if ((e.State & DrawItemState.Selected) == DrawItemState.Selected) 
     { 
      backgroundColor = SystemBrushes.Highlight; 
      textColor = SystemBrushes.HighlightText; 
     } 
     else 
     { 
      backgroundColor = SystemBrushes.Window; 
      textColor = SystemBrushes.WindowText; 
     } 
    } 
    e.Graphics.FillRectangle(backgroundColor, e.Bounds); 
    e.Graphics.DrawString((sender as ComboBox).Items[e.Index].ToString(), font, textColor, e.Bounds); 
} 

这个例子将默认的背景颜色绿色,黑色文本,并且突出显示的项目将具有索引1和3处的项目的红色背景和黑色文本。

您还可以设置ind的字体使用font变量的单个项目。

+1

救了我..非常感谢你:))) –