我写了一个真空管交叉引用程序。 我不知道如何迭代 RichTextBox1 以使请求的管值变为粗体。
搜索 6AU8A 时的现有输出
Tube Cross1 Cross2 Cross3 Qty Location
6AU8 6AU8A 6BH8 6AW8 2 PM BOX 3
6AU8A 6AU8 6BH8 6AW8 6 BOX 9
6BA8A 6AU8 6AU8A 8AU8A 1 BOX 11
6CX8 6AU8A 6EB8 6GN8 2 BOX 16
6EH5 6AU8A 2081 6AW8A# 1 BOX 19
6GH8 6EA8 6GH8A 6AU8A 2 BOX 23
6GH8A 6GH8 6EA8 6AU8A 10 BOX 22
6GH8A 6GH8 6EA8 6AU8A 5 BOX 23
因此,我需要以粗体显示任何搜索词(本例中为 6AU8A)。 使用 VS 2019,针对 .NET 4.8.1 编译的 Windows 应用程序可在 Windows 7 和 10 PC 上运行。
public int FindMyText(string text)
{
length = text.Length;
// Initialize the return value to false by default.
int returnValue = -1;
// Ensure that a search string has been specified and a valid start point.
if (text.Length > 0)
{
// Obtain the location of the first character found in the control
// that matches any of the characters in the char array.
int indexToText = richTextBox1.Find(text);
// Determine whether the text was found in richTextBox1.
if (indexToText >= 0)
{
// Return the location of the character.
returnValue = indexToText;
start = indexToText;
}
}
return returnValue;
}
最佳答案
一旦调用Find()
,该值将被选择(如果存在)。然后您可以更改字体以包括粗体。 Find()
函数有一个“开始”位置,可让您查找下一个出现的位置。因此,您从 0 开始,然后添加搜索字符串的长度以获得下一个起始位置。如果返回的值为 -1,则不再有匹配项,您可以停止。
看起来像这样:
private void button1_Click(object sender, EventArgs e)
{
BoldText("6AU8A"); // get your input from somewhere...
}
private void BoldText(String value)
{
int startAt = 0;
int indexToText = richTextBox1.Find(value, startAt, RichTextBoxFinds.None);
while (indexToText != -1)
{
richTextBox1.SelectionFont = new Font(richTextBox1.SelectionFont, FontStyle.Bold);
startAt = startAt + value.Length;
indexToText = richTextBox1.Find(value, startAt, RichTextBoxFinds.None);
}
}
这是在行动:
关于c# - 遍历 RichTextBox 使特定单词加粗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74744935/