我首先在一个richTextBox里设置好内容(包括格式、颜色),其中包括一些变量,比如[姓名],便于以后用值替换掉;然后保存到数据库的image字段。
然后在使用的时候读取出来,放入richTextBox中,字体格式完全一致。但是我现在想替换掉变量,值的格式完全和变量一致。比如一个人名字叫张三,那这两个字的格式应该完全和[姓名]一致。请问应该如何准确替换呢,希望能给出一些代码,非常感谢。

解决方案 »

  1.   

    你的意思是说 像QQ聊天窗体那样,字体大小颜色改变了,发送出去对方和自己看到的字体与设置的一样?若是那样的话,就要保存字体格式,将字体格式可转化为string类型存入数据库,然后再读取出来不就可以了?当然至少要保存两个参数才生成Font,如Font font= new Font(fontName, fontSize);获取fontName可以用“ 对象.Font.Name” ;fontSize也是如此,类型可为float。字体颜色获取Font.color。在数据库里设计数据表的时候多字体类型,字体大小,字体颜色,这几列而已…不过,也不知道我答的是不是你想要。
      

  2.   

    this.richTextBox1.Rtf,这个是取richtextbox的格式,格式是一串字符,把字符存起来,下次要用的话就是this.richTextBox1.Rtf=数据库里的格式字符
      

  3.   

    多谢楼上各位。如果单是保存字体、颜色、文字那是可以实现的,关键是我现在想读取后进行一定的修改,比如要把所有的[姓名]都替换成张三,如果我用richtextBox.Text = richTextBox.Text.replac('[姓名]','张三') 那所有的格式就都没有了。
    请问应该如何替换呢?
      

  4.   

    暂时是用这个方法解决的,先Find("[姓名]")找到一个index,然后select(index,length),然后设置selectionText。这样就可以保持原来的格式,并且替换掉内容了。
    不过这个应该算外部方法,最好是能直接修改rtf中的文字和格式,期待高手出现。
      

  5.   

    先把要修改的选中,然后获取RichTextBox的选中部分的字体颜色等属性,再把结果替换SelectedText,再按取到的字体颜色设置修改后的文本。
      

  6.   

    参考:private void WriteTextToRichTextBox()
    {
       // Clear all text from the RichTextBox;
       richTextBox1.Clear();
       // Set the font for the opening text to a larger Arial font;
       richTextBox1.SelectionFont = new Font("Arial", 16);
       // Assign the introduction text to the RichTextBox control.
       richTextBox1.SelectedText = "The following is a list of bulleted items:" + "\n";
       // Set the Font for the first item to a smaller size Arial font.
       richTextBox1.SelectionFont = new Font("Arial", 12);
       // Specify that the following items are to be added to a bulleted list.
       richTextBox1.SelectionBullet = true;
       // Set the color of the item text.
       richTextBox1.SelectionColor = Color.Red;
       // Assign the text to the bulleted item.
       richTextBox1.SelectedText = "Apples" + "\n";
       // Apply same font since font settings do not carry to next line.
       richTextBox1.SelectionFont = new Font("Arial", 12);
       richTextBox1.SelectionColor = Color.Orange;
       richTextBox1.SelectedText = "Oranges" + "\n";
       richTextBox1.SelectionFont = new Font("Arial", 12);
       richTextBox1.SelectionColor = Color.Purple;
       richTextBox1.SelectedText = "Grapes" + "\n";
       // End the bulleted list.
       richTextBox1.SelectionBullet = false;
       // Specify the font size and string for text displayed below bulleted list.
       richTextBox1.SelectionFont = new Font("Arial", 16);
       richTextBox1.SelectedText = "Bulleted Text Complete!";
    }
      

  7.   

    多谢hbxtlhx,我也是用这个方法实现的,您看下5,6楼的回复吧。
    但是我觉得最理想的还是能直接修改rtf来实现这些功能。
    还是非常感谢您 ^^