Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
653 views
in Technique[技术] by (71.8m points)

winforms - C# : change listbox items color

i am working on program on windows forms I have a listbox and I am validating data I want the correct data be added to the listbox with color green while the invalid data added with red color and I also want from the listbox to auto scroll down when an item is added and thanks

code :

try
{
    validatedata;
    listBox1.Items.Add("Successfully validated the data  : "+validateddata);
}
catch()
{
    listBox1.Items.Add("Failed to validate data: " +validateddata);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Assuming WinForms, this is what I would do:

Start by making a class to contain the item to add to the listbox.

public class MyListBoxItem {
    public MyListBoxItem(Color c, string m) { 
        ItemColor = c; 
        Message = m;
    }
    public Color ItemColor { get; set; }
    public string Message { get; set; }
}

Add items to your listbox using this code:

listBox1.Items.Add(new MyListBoxItem(Colors.Green, "Validated data successfully"));
listBox1.Items.Add(new MyListBoxItem(Colors.Red, "Failed to validate data"));

In the properties of the ListBox, set DrawMode to OwnerDrawFixed, and create an event handler for the DrawItem event. This allows you to draw each item however you wish.

In the DrawItem Event:

private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
    MyListBoxItem item = listBox1.Items[e.Index] as MyListBoxItem; // Get the current item and cast it to MyListBoxItem
    if (item != null) 
    {
        e.Graphics.DrawString( // Draw the appropriate text in the ListBox
            item.Message, // The message linked to the item
            listBox1.Font, // Take the font from the listbox
            new SolidBrush(item.ItemColor), // Set the color 
            0, // X pixel coordinate
            e.Index * listBox1.ItemHeight // Y pixel coordinate.  Multiply the index by the ItemHeight defined in the listbox.
        );
    }
    else 
    {
         // The item isn't a MyListBoxItem, do something about it
    }
}

There are a few limitations - the main one being that you'd need to write your own click handler and redraw appropriate items to make them appear selected, since Windows won't do that in OwnerDraw mode. However, if this is just intended to be a log of things happening in your application, you may not care about items appearing selectable.

To scroll to the last item try

listBox1.TopIndex = listBox1.Items.Count - 1;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...