Resolved listbox line color change

Katonas

Member
Joined
Sep 6, 2022
Messages
6
Programming Experience
Beginner
Hello
I am new to c# and I am trying to write simple code for listing all .ini files in directories. And now I need each line to be green or red depending on the context of .ini files. My code seems like just go through all files in listbox and color all lines depending on value of the last .ini.
Thanks

C#:
namespace WindowsFormsApp2
{
    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string rootdir = @"C:\Users\isaced1\Desktop\test";

            string[] files = Directory.GetFiles(rootdir, "*.ini", SearchOption.AllDirectories);
            Projects.Items.AddRange(files);
            //var items = Projects.SelectedItems;
            foreach (var item in files)
            {
                try
                {
                    string fileName = Projects.GetItemText(item);
                    string fileContents = System.IO.File.ReadAllText(fileName);
                    const string PATTERN = @"OTPM              = true";
                    Match match = Regex.Match(fileContents, PATTERN, RegexOptions.IgnoreCase);
                    if (match.Success)
                    {
                        Projects.ForeColor = Color.Green;
                    }
                    else
                    {
                        Projects.ForeColor = Color.Red;
                    }
                }
                catch
                {
                    MessageBox.Show("No");
                }
            }

        }
    }
}
 
You're just changing the text colour in the control. The items have no properties for colour. What you need to do is owner-draw the items and specify the appropriate colour(s) then. I suggest that you read this, make your best attempt to implement what you learn and then post back if you encounter a specific issue. Note that you will have to store the information indicating how to colour each file when you read them in the first place, because you don't want to have to read them every time the items get drawn as that can be multiple times.
 
Back
Top Bottom