RichTextBox - 计算不包括wordwrap的行

时间:2017-04-11 18:04:55

标签: .net vb.net

我有下面的代码,用于搜索和替换richtextbox中的文本,但是当wordwrap打开时,似乎会丢弃linecount,它会替换错误的行或错误。

所以这就是它应该如何工作(而且确实如此,而不是当wordwrap = true时)。


我们说我有一个富文本框,上面写着“#Hello; Hello World blah blah"

第1步。我输入" StackOverflow"进入textbox1。

第2步。当textbox1.textchanged时,我调用SandR(" Hello world",textbox1.text.trim," blah blah"

第3步。输出应为" Hello world StackOverflow blah blah"

现在使用以下代码,这是有效的。但是,当richtextbox中的文本足够长以触发wordwrap时,它将停止工作。例如:

Stack Overflow, !

This community restores my faith in humanity. Time and time again, people like  continuously reach out to community questions and help people like me who are struggling to figure out code. It is a learning process for us, and you folks are a great example of what it means to be a good human being.

Thank you all so much for helping users like myself save countless hours of reading material on the internet (that may or may not work due to outdated code, etc) and giving us a chance to learn from someone who is responding to us in real time.

Thanks again !

现在如果那个文字有自动换行,我试图做SandR("再次感谢",textbox1.text.trim," LarsTech!")它会失败。

我是否可以对此代码进行任何修改以避免此问题?

Function SandR(ByVal Search As String, ControlText As Object, Replace As String) As String
        Dim text = ""
        Dim startindex = 0
        Dim endindex = 0
        Try
            For i As Integer = 0 To txtRTB.Lines.Length - 1
                text = txtRTB.Lines(i)
                If text.Contains(Search) = True Then
                    startindex = txtRTB.GetFirstCharIndexFromLine(i)
                    endindex = text.Length
                    txtRTB.[Select](startindex, endindex)
                    txtRTB.Text = txtRTB.Text.Replace(txtRTB.SelectedText, Search & ControlText.Text.Trim & Replace)
                End If
            Next
        Catch
            For i As Integer = 0 To txtRTB.Lines.Length - 1
                text = txtRTB.Lines(i)
                If text.Contains(Search) = True Then
                    startindex = txtRTB.GetFirstCharIndexFromLine(i)
                    endindex = text.Length
                    txtRTB.[Select](startindex, endindex)
                    txtRTB.Text = txtRTB.Text.Replace(txtRTB.SelectedText, Search & ControlText.Trim & Replace)
                End If
            Next
        End Try
    End Function



对于LarsTech:
所以这就是我使用textchanged时的样子:http://imgur.com/a/T49eq
这就是我使用按钮时的样子:http://imgur.com/jH5RCDV
这是我更改文本框并再次点击按钮时的样子:http://imgur.com/rIkyxvH

1 个答案:

答案 0 :(得分:0)

我会删除Try..Catch,因为发生的任何异常肯定都在你的控制范围内以避免它。

当您想要替换文本时,似乎没有必要通过Lines集合,因此请尝试向后遍历文本 ,因为替换文本会干扰索引位置。

function test(svc: Service) {
    svc.method1();
}

此外,您的功能不会返回任何内容,因此将其转换为Sub例程。