c# - 如何使用 VB.NET 以编程方式在 Richtextbox 中添加粗体文本

标签 c# vb.net richtextbox

我有这个代码:

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

最佳答案

当使用 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

结果:

RichTextBox with bold text

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()

关于c# - 如何使用 VB.NET 以编程方式在 Richtextbox 中添加粗体文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12775387/

相关文章:

c# - RichTextBox.Select 与 SubString 方法之间的行为不一致

c# - 如何在 C# 的富文本框中为文本着色?

c# - 在 C# 中,如何将泛型类型参数约束为仅接受可为 null 的值类型?

asp.net - 相同命名空间中的相同类名

c# - 我的多线程 HttpClient 有什么问题吗?

mysql - Crystal 报表公式创建vb.net mysql

.net - FlowLayoutPanel - 控件的自动宽度?

c# - 富文本框 - 粗体

c# - 将函数(委托(delegate)?)传递给期望对象作为参数的函数

c# - 将 ushort 图像转换为二进制?