首页 > 解决方案 > ListBox 按条件更改元素的文本颜色

问题描述

例如,如果其中出现“错误”一词,如何更改行的文本颜色,我可以想象如何进行检查,但是无法更改一个元素的颜色。我将不胜感激您的帮助!

private void LoadFTP()
{
    listBox2.Items.Clear();
    FtpWebRequest reqFTP = (FtpWebRequest)WebRequest.Create("ftp://ServerIP/Logs/"+path);
    reqFTP.UsePassive = false;
    reqFTP.UseBinary = true;
    reqFTP.Credentials = new NetworkCredential("Login", "Password");
    reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
    reqFTP.Proxy = GlobalProxySelection.GetEmptyWebProxy();
    FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
    using (Stream stream = response.GetResponseStream())
    {
        StreamReader reader = new StreamReader(stream, Encoding.UTF8);
        string line;
        while ((line = reader.ReadLine()) != null)
        {
            listBox2.Items.Add(line);
            listBox2.TopIndex = listBox2.Items.Count - 1;
        }
        // Console.WriteLine("Upload File Complete, status {0}", responseString); 
        stream.Close();
    }
    response.Close(); //Closes the connection to the server
}

PS我不太懂英语,但你有一个比俄罗斯更充足的社区。

标签: c#winformslistbox

解决方案


您可以尝试使用 ListView 代替 ListBox

private void FillListView()
{
    for(int i = 0; i < 10; i++)
    {
        if (i == 9)
            listView1.Items.Add(new ListViewItem($"number {i}") {ForeColor = Color.Green });
        else
            listView1.Items.Add(new ListViewItem($"number {i}"));
    }
}

但是如果你需要 ListBox 我认为你只能通过 Draw_Item 事件来做到这一点。


推荐阅读