【问题标题】:How to add a bold text in Rich TextBox programatically using VB.NET如何使用 VB.NET 以编程方式在 Richtextbox 中添加粗体文本
【发布时间】:2013-02-28 23:47:49
【问题描述】:

我有这个代码:

print_text.Text = "Patient number: " + ds.Tables("patients").Rows(0).Item(0)
print_text.AppendText(Environment.NewLine)
print_text.Text = print_text.Text + "Last name: " + ds.Tables("patients").Rows(0).Item(1)
print_text.AppendText(Environment.NewLine)

现在我以编程方式添加上述数据,它工作正常。但是在上面的代码中,我想以粗体添加Patient numberLast name

【问题讨论】:

    标签: c# vb.net richtextbox


    【解决方案1】:

    当使用RichTextBox 时,为什么不直接使用 RTF?


    示例:

    Sub Main
        Dim f = new Form()
        Dim print_text = new RichTextBox() With {.Dock = DockStyle.Fill}
        f.Controls.Add(print_text)
    
        Dim sb = new System.Text.StringBuilder()
        sb.Append("{\rtf1\ansi")
        sb.Append("This number is bold: \b 123\b0 ! Yes, it is...")
        sb.Append("}")
        print_text.Rtf = sb.ToString()
    
        f.ShowDialog()
    End Sub
    

    结果:

    MSDN


    这样,您还可以轻松地将 RTF 内容包装到扩展方法中:

    Module RtfExtensions
    
        <Extension()>
        Public Function ToRtf(s As String) As String
            Return "{\rtf1\ansi" + s + "}"
        End Function
    
        <Extension()>
        Public Function ToBold(s As String) As String
            Return String.Format("\b {0}\b0 ", s)
        End Function
    
    End Module
    

    并像使用它

    Dim text = "This number is bold: " + "123".ToBold() + "! Yes, it is..."
    print_text.Rtf = text.ToRtf()
    

    【讨论】:

    • 不错的解决方案,我喜欢。
    【解决方案2】:

    使用RichTextBox.SelectionFont 属性。
    查看这些 MSDN 链接以了解如何执行此操作:Link 1Link 2

    希望对您有所帮助。
    编辑:

      Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim len As Integer
        RichTextBox1.Text = "Patient number: " + " 12345"
        RichTextBox1.SelectionStart = 0
        RichTextBox1.SelectionLength = "Patient number".Length
        RichTextBox1.SelectionFont = New Font("Arial", 12, FontStyle.Bold)
        RichTextBox1.SelectionLength = 0
        RichTextBox1.AppendText(Environment.NewLine)
        len = RichTextBox1.Text.Length
        RichTextBox1.AppendText("Last name: " + " ABCD")
        RichTextBox1.SelectionStart = len
        RichTextBox1.SelectionLength = "Last name".Length
        RichTextBox1.SelectionFont = New Font("Arial", 12, FontStyle.Bold)
        RichTextBox1.SelectionLength = 0
    End Sub
    

    【讨论】:

    • 这是一个选定的文本。我想要的是我动态添加到富文本框的数据应该是粗体
    • 它与动态或静态无关。您可以在任何地方使用此属性,但需要适当地使用它。我已经更新了我的答案以包含一个简单的示例。请看一看。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2018-11-02
    • 2019-01-30
    • 1970-01-01
    • 2012-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多