根据条件更改列表框项目的颜色

时间:2019-02-19 23:18:42

标签: c# .net

我正在尝试根据条件更改列表框中线条的颜色。列表框将显示一个列表对象,该列表对象是名称,然后计算该人的未来年龄。

如果年龄小于5岁或介于6至18岁之间,我会尝试设置线条的颜色。

DateTime futureDate = dateTimePicker3.Value;

        foreach (ChildDetails c in children)
        {
            int Age = futureDate.Year - c.DOB.Year;

            if (c.DOB > futureDate.AddYears(-Age))
            {
                Age--;
            }

            if (Age <= 5)
            {
                this.listBox4.ForeColor = Color.Yellow;
            }
            else if (Age >= 6 && Age <= 18)
            {
                this.listBox4.ForeColor = Color.Green;
            }
            else
            {
                this.listBox4.ForeColor = Color.Red;
            }

            listBox4.Items.Add($" {c.name} {Age}");            
        }

2 个答案:

答案 0 :(得分:1)

如果改用ListView,则可以指定每个项目的Forecolor(和/或Backcolor)。例如,在表单上放置一个ListView并尝试以下代码:

private void Form1_Load(object sender, EventArgs e)
{
    listView1.View = View.List;
    var items = new Dictionary<string, int>
    {
        {"Shaggy", 4},
        {"Fred", 6},
        {"Daphne", 10},
        {"Velma", 16},
        {"Scooby", 20},
    };

    foreach (var item in items)
    {
        int age = item.Value;
        Color foreColor;
        Color backColor;

        if (age <= 5)
        {
            foreColor = Color.Yellow;
            backColor = Color.Purple;
        }
        else if (age >= 6 && age <= 18)
        {
            foreColor = Color.Green;
            backColor = Color.BurlyWood;
        }
        else
        {
            foreColor = Color.Red;
            backColor = Color.CornflowerBlue;
        }

        listView1.Items.Add(new ListViewItem
        {Text = item.Key, ForeColor = foreColor, BackColor = backColor});
    }
}

输出

![enter image description here

答案 1 :(得分:-1)

只需创建一个listboxItem并更改该listBoXItem的前景色或背景色,然后将其插入到listbox中即可。 here is a link that can help you