【问题标题】:ListBox change the element's text color by conditionListBox 按条件更改元素的文本颜色
【发布时间】:2021-08-10 19:26:03
【问题描述】:

如何更改一行的文本颜色,例如,如果其中出现“错误”一词,我可以想象如何进行检查,但是没有办法更改一个元素的颜色。非常感谢您的帮助!

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
}

附:我不太懂英语,但你的社区比俄语社区更完善。

【问题讨论】:

  • 如果这是 WinForms,则必须查看 DrawMode 属性和 DrawItem 事件。
  • @LarsTech,我试着按照stackoverflow.com/a/45069356/4796672的答案去做。但是我有一个问题,当点击一个元素时,文本会扭曲,滚动时是一样的。现在就我而言,我已经禁用了元素的选择。
  • 另一个例子:ListBox.DrawItem Event。请注意,它还会绘制背景和选择矩形以正确显示所选项目。
  • 如果您对此有任何疑问,您必须向我们展示您的代码

标签: c# winforms listbox


【解决方案1】:

你可以试试用 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 事件来实现。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-20
    • 2017-08-08
    • 1970-01-01
    • 2021-01-09
    • 2013-03-23
    • 2021-01-06
    • 2023-03-06
    • 1970-01-01
    相关资源
    最近更新 更多