2014-05-25 6 views
1

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

나는에 ListBox1에 DateTimePicker1에서 TextBox1에에서 텍스트와 시간과 날짜를 추가 할 수 있습니다.

현재 시간에서 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); 
} 

내가 여기 사용하고 DrawItemEventArgs의 다양한 구성원에 대한 자세한 내용은 this page를 참조하십시오.

+0

작동하려면 : ( – user3215507

+0

당신은 어떤 종류의 문제에 대해 구체적으로해야합니다. –

+0

색깔이 변하지 않습니다. 문제가 'DateTime itemTime, deadline = DateTime.Now.AddHours (1); var brush = (DateTime.TryParse (itemText, out itemTime) && itemTime user3215507

관련 문제