如何检查richtextbox中的新行是否为空

How to check if new line is empty in richtextbox

我正在检查 richtextbox 中的一行是否为空。如果没有,它将进入下一行。 我使用的代码是:

Dim text as string="hello"
Dim lines = RichTextBox1.Lines
Dim upperBound = lines.GetUpperBound(0)

If lines(upperBound).Trim() = String.Empty Then
   lines(upperBound) = text
   RichTextBox1.Lines = lines
Else
    RichTextBox1.AppendText(Environment.NewLine & text)
End If

效果很好。但是刚才发现如果Richtextbox1完全是空的,这段代码是不会往里面添加文字的。有什么办法可以修复这个小错误吗?谢谢

尝试:

Dim text as string="hello"
Dim lines = RichTextBox1.Lines
Dim empty = {""}

If lines.Length = 0 Then lines = empty
    
Dim upperBound = lines.GetUpperBound(0)

If lines(upperBound).Trim() = String.Empty Then
    lines(upperBound) = titolo
    RichTextBox1.Lines = lines
Else
    RichTextBox1.AppendText(Environment.NewLine & text)
End If

你可以试试这个非常高效的系统。

这叫做LinQ for array,你可以查询一个空行的数组, 如果计数大于 0 则退出(或给出错误)

Dim text As String = "hello"
Dim lines = RichTextBox1.Lines
        Dim qry = From n In lines
                  Where n = ""
                  Select n
        If qry.Count > 0 Then
        'you can give some error here
        End If

看看这是否符合您的要求:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim text As String = "hello"

    If RichTextBox1.Text.Trim = "" Then
        RichTextBox1.AppendText(titolo)
    ElseIf RichTextBox1.Lines(RichTextBox1.Lines.GetUpperBound(0)).Length = 0 Then
        RichTextBox1.AppendText(titolo)
    ElseIf RichTextBox1.Lines(RichTextBox1.Lines.GetUpperBound(0)).Trim = "" Then
        Dim lines = RichTextBox1.Lines
        lines(lines.GetUpperBound(0)) = titolo
        RichTextBox1.Lines = lines
    Else
        RichTextBox1.AppendText(Environment.NewLine & text)
    End If
End Sub