In a combo box values if contains * mark I want to change that item text color to different color. If value doesn't contain * I don't need to change that item text color. How can I do it?
You can do by this
make a class that contain two properties for exmaple
public class Product
{
public string ProductName { get; set; }
public Int32 ProductStatus { get; set; }
}
and then add your items in a list on form load
private void Form1_Load(object sender, EventArgs e)
{
List<Product> listPdt = new List<Product>();
Product pdt = new Product();
pdt.ProductName = "Product 1";
pdt.ProductStatus = 1;
listPdt.Add(pdt);
Product pdt1 = new Product();
pdt1.ProductName = "Product 1*";
pdt1.ProductStatus = 1;
listPdt.Add(pdt1);
Product pdt2 = new Product();
pdt2.ProductName = "Product 2";
pdt2.ProductStatus = 1;
listPdt.Add(pdt2);
Product pdt3 = new Product();
pdt3.ProductName = "Product 2*";
pdt3.ProductStatus = 1;
listPdt.Add(pdt3);
comboBox1.DataSource = listPdt;
comboBox1.DisplayMember = "ProductName";
comboBox1.ValueMember = "ProductStatus";
// this will fire combo box's draw event.
comboBox1.DrawMode = DrawMode.OwnerDrawVariable;
}
Now Write combobox's draw event
private void comboBox1_DrawItem(object sender, DrawItemEventArgs e)
{
Brush brush = null;
ComboBox combo;
try
{
e.DrawBackground();
combo = (ComboBox)sender;
Product pdt = (Product)combo.Items[e.Index];
if (pdt.ProductName.Contains("*"))
{
brush = Brushes.Red;
}
else
{
brush = Brushes.Black;
}
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
e.Graphics.DrawString(pdt.ProductName, combo.Font, brush, e.Bounds.X, e.Bounds.Y);
}
catch (Exception Ex)
{
}
}
if you have list that are coming from database then add them to list by foreach loop and fill the list class.
Following code, checks if the current SelectedItem
contains a * mark
, event gets fired everytime the selectedIndexChanges:
private void ComboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if(ComboBox1.SelectedItem.ToString().Contains("*"))
{
//Change color here
ComboBox1.BackColor = Color.Red;
}
}
If you want to iterate through all items in the ComboBox on load of the form, use following code, where you are able to modify each item that contains a * mark
.
private void Form1_Load(object sender, EventArgs e)
{
foreach(var item in ComboBox1.Items)
{
if(item.ToString().Contains("*"))
{
//Modify item color here
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.