C# 中在列表框中标记找到的文本为红色。

huangapple go评论64阅读模式
英文:

C# mark found TEXT in listbox in red

问题

我怎样在我的列表框中标记找到的文本?首先,我使用以下代码搜索包含的文本:

bool found = false;
foreach (var item in listBox1.Items)
{
if(item.ToString().Equals("STOP"))
{
found = true;
break;
}
}
if(!found)
用红色标记它。


我想在找到“STOP”后将整个文本以红色突出显示。谢谢!
英文:

How can I mark a found TEXT in my listbox? First I'm searching for contain using this:

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

I want to highlight all the entire TEXT in red after finding the "STOP". Thank you!

答案1

得分: 0

你应该使用ListBox1_DrawItem 来改变文本颜色。

示例代码:

public Form1()
{
    InitializeComponent();
    listBox1.DrawItem += ListBox1_DrawItem;
    listBox1.DrawMode = DrawMode.OwnerDrawFixed;

    // 示例数据
    listBox1.Items.Add("24 CALL LBL 1");
    listBox1.Items.Add("25 L X+100 Y-150 R0 FMAX M92");
    listBox1.Items Add("26 STOP");
    listBox1.Items.Add("STOP");
}

private void ListBox1_DrawItem(object? sender, DrawItemEventArgs e)
{
    ListBox lb = (ListBox)sender;
    var itemText = lb.Items[e.Index].ToString();
    var textColor = Color.Black;
    if(itemText.Contains("STOP")) textColor = Color.Red;

    e.DrawBackground();
    Graphics g = e.Graphics;       
    g.DrawString(lb.Items[e.Index].ToString(), e.Font, new SolidBrush(textColor), new PointF(e.Bounds.X, e.Bounds.Y));
    e.DrawFocusRectangle();
}

但我认为使用ListView 更好。您可以参考以下链接:ListView更好的选择

英文:

You should use the ListBox1_DrawItem to change the text color.

Sample Code:

public Form1()
{
    InitializeComponent();
    listBox1.DrawItem += ListBox1_DrawItem;
    listBox1.DrawMode = DrawMode.OwnerDrawFixed;

    // Sample Data
    listBox1.Items.Add("24 CALL LBL 1");
    listBox1.Items.Add("25 L X+100 Y-150 R0 FMAX M92");
    listBox1.Items.Add("26 STOP");
    listBox1.Items.Add("STOP");
}

private void ListBox1_DrawItem(object? sender, DrawItemEventArgs e)
{
    ListBox lb = (ListBox)sender;
    var itemText = lb.Items[e.Index].ToString();
    var textColor = Color.Black;
    if(itemText.Contains("STOP")) textColor = Color.Red;

    e.DrawBackground();
    Graphics g = e.Graphics;       
    g.DrawString(lb.Items[e.Index].ToString(), e.Font, new SolidBrush(textColor), new PointF(e.Bounds.X, e.Bounds.Y));
    e.DrawFocusRectangle();
}

C# 中在列表框中标记找到的文本为红色。

But I think ListView is better
https://stackoverflow.com/questions/2554609/c-sharp-changing-listbox-row-color

huangapple
  • 本文由 发表于 2023年3月7日 14:47:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/75658749.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定