2014-05-25 104 views
1

我需要幫助改變列表框中特定項目的顏色。更改列表框顏色如果

我的代碼:

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";   
     }  
    } 
} 

我從DateTimePicker1添加從TextBox1的文本和時間和日期listBox1中。

如果當前時間少於1小時,我需要列表框中的項目變成紅色。

我試過到目前爲止:

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

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

如果你能完成這個還是有不同的解決方案,這將是巨大的。

謝謝!

+0

請參閱[ListBox.DrawItem事件](http://msdn.microsoft.com/en-us/library/system.windows.forms.listbox.drawitem(v = vs.110).aspx) – LarsTech

回答

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); 
} 

參考this page上的DrawItemEventArgs各成員,我在這裏使用的詳細信息。

+0

無法獲取此內容要工作:( – user3215507

+0

你必須具體說明你有什麼樣的問題 –

+0

顏色不會改變,也許問題出在'DateTime itemTime,截止日期= DateTime.Now.AddHours(1); var brush =(DateTime.TryParse(itemText,out itemTime)&& itemTime user3215507