英文:
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();
}
But I think ListView is better
https://stackoverflow.com/questions/2554609/c-sharp-changing-listbox-row-color
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论