以下所有代码都会删除TextBox
中的所有空行。
但是我希望单击按钮时光标指针线被移除。
'First method
TextBox2.Lines = TextBox2.Lines.Where(Function(l) Not String.IsNullOrWhiteSpace(l)).ToArray()
Dim count = TextBox2.Lines.Length
'Second method
Dim tmp() As String = TextBox2.Text.Split(CChar(vbNewLine))
TextBox2.Clear()
For Each line As String In tmp
If line.Length > 1 Then
TextBox2.AppendText(line & vbNewLine)
End If
Next
'Third method
Dim SearchIn = Me.TextBox2.Text
Dim sb As StringBuilder = New StringBuilder(SearchIn)
Me.TextBox2.Text = sb.Replace(vbCrLf + vbCrLf, vbCrLf).ToString
'Fourth method
TextBox2.Text = Regex.Replace(TextBox2.Text, "(?<Text>.*)(?:[\r\n]?(?:\r\n)?)", "${Text} ") + "/n"
TextBox2.Text = Replace(TextBox2.Text, vbCrLf & vbCrLf, vbCrLf)
答案 0 :(得分:0)
要从TextBoxBase
派生控件(TextBox,RichTextBox)中删除一行文本,首先必须确定正确的行。
如果包含文本,则无法使用.Lines属性,因为它将返回相对于未包装文本的行号。
您可以使用GetLineFromCharIndex()获取当前包装的行。 Integer参数是当前插入符号位置,由SelectionStart
属性引用。
此行的第一个字符索引由GetFirstCharIndexFromLine()后退。
然后,找到当前行长度,识别第一个换行符。添加换行符号的长度以将其包含在计算长度中。
请注意,TextBox
控件使用Environment.Newline生成换行符(&#34; \r\n
&#34;),而RichTextBox
控件仅使用换行符(&#34; \n
&#34)。
这将删除插入符号当前所在的任何行:
(如果您只想删除空白行,请检查行长度是否为< 3
)。
Dim CurrentPosition As Integer = TextBox2.SelectionStart
Dim CurrentLine As Integer = TextBox2.GetLineFromCharIndex(CurrentPosition)
Dim LineFirstChar As Integer = TextBox2.GetFirstCharIndexFromLine(CurrentLine)
Dim LineLenght As Integer = TextBox2.Text.
IndexOf(Environment.NewLine, LineFirstChar) - LineFirstChar +
Environment.NewLine.Length
If LineLenght <= 0 Then Return
TextBox2.Select(LineFirstChar, LineLenght)
TextBox2.SelectedText = TextBox2.SelectedText.Remove(0)
TextBox2.SelectionLength = 0
TextBox2.SelectionStart = If(CurrentPosition < TextBox2.Text.Length, LineFirstChar, TextBox2.Text.Length)
TextBox2.Focus()
这将删除包含插入符号的整个段落:
Dim CurrentPosition As Integer = TextBox2.SelectionStart
Dim ParagraphFirstIndex As Integer = TextBox2.Text.
LastIndexOf(Environment.NewLine, CurrentPosition) +
Environment.NewLine.Length
Dim LineFeedPosition As Integer = TextBox2.Text.IndexOf(Environment.NewLine, ParagraphFirstIndex)
LineFeedPosition = If(LineFeedPosition > -1, LineFeedPosition + Environment.NewLine.Length, TextBox2.Text.Length)
Dim LineLenght As Integer = LineFeedPosition - ParagraphFirstIndex
If LineLenght <= 0 Then Return
TextBox2.Select(ParagraphFirstIndex, LineLenght)
TextBox2.SelectedText = TextBox2.SelectedText.Remove(0)
TextBox2.SelectionLength = 0
TextBox2.SelectionStart = If((CurrentPosition < TextBox2.Text.Length), ParagraphFirstIndex, TextBox2.Text.Length)
TextBox2.Focus()