You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C# ListBox中将找到的文本标记为红色?

在ListBox中标记找到的文本

根据你的需求,分两种场景给出实现方案(以C# WinForms为例,你的代码风格符合该框架):

场景1:找到"STOP"后将整个ListBox的所有文本设为红色

直接修改控件的前景色即可,调整你的代码如下:

bool found = false;
foreach (var item in listBox1.Items)
{
    if (item.ToString().Equals("STOP"))
    {
        found = true;
        break;
    }
}

if (found)
{
    // 将ListBox所有文本设置为红色
    listBox1.ForeColor = Color.Red;
}
else
{
    // 未找到时恢复默认文本颜色
    listBox1.ForeColor = SystemColors.ControlText;
}

场景2:仅高亮找到的"STOP"项(而非所有文本)

WinForms默认ListBox不支持单独设置某一项的颜色,需要开启自绘模式:

  1. 先在窗体设计器中,将listBox1的DrawMode属性设置为OwnerDrawFixed
  2. 添加DrawItem事件处理代码:
private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
    e.DrawBackground();
    
    string itemContent = listBox1.Items[e.Index].ToString();
    // 仅当项内容为"STOP"时用红色绘制
    Brush textBrush = new SolidBrush(itemContent.Equals("STOP") ? Color.Red : e.ForeColor);
    
    e.Graphics.DrawString(itemContent, e.Font, textBrush, e.Bounds);
    e.DrawFocusRectangle();
    
    textBrush.Dispose();
}

如果需要找到"STOP"后自动选中该项,可以在查找代码中添加选中逻辑:

bool found = false;
for (int i = 0; i < listBox1.Items.Count; i++)
{
    if (listBox1.Items[i].ToString().Equals("STOP"))
    {
        found = true;
        listBox1.SelectedIndex = i; // 选中找到的项
        break;
    }
}

内容的提问来源于stack exchange,提问作者Wadim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 07:22:54