First Create a CustomComboBox control, with this C# code:
using System; using System.Windows.Forms; using System.Drawing; namespace TyroDeveloperDLL { public class ComboBoxCustom : ComboBox { public ComboBoxCustom() { this.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed; } protected override void OnDrawItem(DrawItemEventArgs e) { base.OnDrawItem(e); if (e.Index < 0) { return; } e.DrawBackground(); ComboBoxItem item = (ComboBoxItem)this.Items[e.Index]; Brush brush = new SolidBrush(item.ForeColor); if ((e.State & DrawItemState.Selected) == DrawItemState.Selected) { brush = Brushes.Yellow; } e.Graphics.DrawString(item.Text, this.Font, brush, e.Bounds.X, e.Bounds.Y); } object selectedValue = null; public new Object SelectedValue { get { object ret = null; if (this.SelectedIndex >= 0) { ret = ((ComboBoxItem)this.SelectedItem).Value; } return ret; } set { selectedValue = value; } } string selectedText = ""; public new String SelectedText { get { return ((ComboBoxItem)this.SelectedItem).Text; } set { selectedText = value; } } } public class ComboBoxItem { public ComboBoxItem() { } public ComboBoxItem(string pText, object pValue) { text = pText; val = pValue; } public ComboBoxItem(string pText, object pValue, Color pColor) { text = pText; val = pValue; foreColor = pColor; } string text = ""; public string Text { get { return text; } set { text = value; } } object val; public object Value { get { return val; } set { val = value; } } Color foreColor = Color.Black; public Color ForeColor { get { return foreColor; } set { foreColor = value; } } public override string ToString() { return text; } } }To add the ComboBox Items:
comboBoxCustom1.Items.Add(new ComboBoxItem("México","0",Color.Green)); comboBoxCustom1.Items.Add(new ComboBoxItem("USA", "1", Color.Blue)); comboBoxCustom1.Items.Add(new ComboBoxItem("China", "2", Color.Red));
Too is possible add items from a database with a DataReader:
OleDbConnection cnn = new OleDbConnection(Class.clsMain.CnnStr); try { string SQL = "SELECT ID_SUBDIVISION, SUBDIVISION "+ " FROM SUBDIVISION WHERE [ENABLED]=TRUE"; cnn.Open(); OleDbCommand cmd = new OleDbCommand(); cmd.Connection = cnn; cmd.CommandText = SQL; OleDbDataReader dr = cmd.ExecuteReader(); while (dr.Read()) { cbo.Items.Add(new ComboBoxItem(dr["SUBDIVISION"].ToString(), dr["ID_SUBDIVISION"], Color.Blue));//Set your color here } dr.Close(); cbo.SelectedIndex = 0; } catch (Exception ex) { throw (ex); } finally { cnn.Close(); }
Please Click on the +1 button
Any chance this is possible in Excel 2010 VBA?
ResponderEliminar