Bold in RichtextBox

我们两清 提交于 2019-11-30 18:50:01

问题


I've been working on my richtextbox but I ran into something weird... I want to make the first word on everyline bold

using this code:

        RichTextBox bold = richTextBox1;
        foreach (string line in bold.Lines)
        {
            string name = line.Split(' ')[0];
            int srt = bold.Find(name);
            bold.Select(srt, name.Length);
            bold.SelectionFont = new Font(bold.Font, FontStyle.Bold);
        } 

But for some reason some lines are skipped. From what I noticed it depends on what word the line starts with

e.g Name: gets skipped but Name1: is fine, the same happens with ProcessId, VirtualSize and WorkingSetSize.

If any more explanation is required please tell me.

The lines are added like

richTextBox1.Text += "Name: "+ queryObj["Name"] + Environment.NewLine;

the function to make all first words bold is called after all the content is added to the richtextbox.


回答1:


The line...

int srt = bold.Find(name);

...is finding the first occurrence of the word that starts the line. If you look at the words that haven't been set bold then you will see that they all occur earlier in the rich text box.




回答2:


My richtextbox wasn't selecting all the occurrences if they weren't sent to my bolding function in the right order; so my fix includes checking that start (srt) is greater than 0 before starting the text selection. It goes something like this:

foreach (string line in bold.Lines)
{
    int srt = bold.Find(name);
    if (srt > 0)
    {
        bold.Select(srt, name.Length);
        bold.SelectionFont = new System.Drawing.Font(bold.Font, FontStyle.Bold);
    }
}

And now it'll always select the first occurrence.

PS: name is a string, and bold is a RichTextBox.



来源:https://stackoverflow.com/questions/9314288/bold-in-richtextbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!