更改listBox颜色if

时间:2014-05-25 15:51:11

标签: c# visual-studio datetime listbox

我需要帮助改变listBox中特定项目的颜色。

我的代码:

namespace WindowsFormsApplication6
{
    public partial class Form2 : Form
    {
        List<string> lst;


        public Form2()
        {
            InitializeComponent();
            dateTimePicker1.Format = DateTimePickerFormat.Custom;
            dateTimePicker1.CustomFormat = "dd/MM/yyyy  HH:mm";
            lst = new List<string>();   
        }

        private void BindList()
        {
            lst = (lst.OrderByDescending(s => s.Substring(s.LastIndexOf(" "), s.Length - s.LastIndexOf(" ")))).ToList();
            listBox1.DataSource = lst;
        }

        private void button1_Click(object sender, EventArgs e)
        {       
                string s = textBox1.Text + ", " + Convert.ToDateTime(this.dateTimePicker1.Value).ToString("dd/mm/yyyy HH:mm");
                lst.Add(s);
                BindList();

        }

        private void button2_Click(object sender, EventArgs e)
        {
            lst.Remove(listBox1.SelectedItem.ToString());
            BindList();    
        }

        private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
        {
            dateTimePicker1.CustomFormat = "dd/MM/yyyy  HH:mm";        
        }       
    }
}

我将TextBox1中的文本以及DateTimePicker1中的时间和日期添加到listBox1。

如果距离当前时间不到1小时,我需要列表框中的项目变为红色。

到目前为止我已尝试过:

DateTime current = System.DateTime.Now.AddHours(+1);
DateTime deadline = Convert.ToDateTime(dateTimePicker1.Value);

do
{
   // missing this part
}
   while (current <= deadline); 

如果你能完成这个或有不同的解决方案,那就太好了。

谢谢!

1 个答案:

答案 0 :(得分:0)

初始化表单时,您会想要这样的内容:

listBox1.DrawMode = DrawMode.OwnerDrawFixed;
listBox1.DrawItem += listBox1_DrawItem;

第一行表示列表框的项目将由您提供的代码绘制,第二行指定将执行绘图的事件处理程序。然后你只需要创建listBox1_DrawItem()方法。这样的事情应该做:

private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
    // DrawItemEventArgs::Index gives you the index of the item being drawn.
    var itemText = listBox1.Items[e.Index].ToString();

    // Get a red brush if the item is a DateTime less than an hour away, or a black
    // brush otherwise.
    DateTime itemTime, deadline = DateTime.Now.AddHours(1);
    var brush = (DateTime.TryParse(itemText, out itemTime) && itemTime < deadline) ? Brushes.Red : Brushes.Black;

    // Several other members of DrawItemEventArgs used here; see class documentation.
    e.DrawBackground();
    e.Graphics.DrawString(itemText, e.Font, brush, e.Bounds);
}

有关我在此处使用的DrawItemEventArgs各成员的详细信息,请参阅this page

相关问题