【问题标题】:Reading lines in textbox individually单独读取文本框中的行
【发布时间】:2012-08-24 12:47:12
【问题描述】:

我正在尝试单独读取文本框中的每一行并检查它是否包含某个字符串。这将在文本框的 textchanged 事件中用于检查某个字符串,如果找到,它将执行相应的代码。

我无法让它正常工作。这是我的代码。

    Dim txt As FastColoredTextBox = TryCast(page.Controls(0), FastColoredTextBox)
        For Each line As Line In txt.Lines
            If CBool(InStr(line.ToString(), "<vb>")) Then
                txt.Language = Language.VB
            End If

【问题讨论】:

  • 它在做什么,你期望它做什么?

标签: vb.net visual-studio vb.net-2010


【解决方案1】:

FastColoredTextBox.Lines 是一个 List(Of String),因此您可以简单地以这种方式在 Lines 上循环

Dim txt As FastColoredTextBox = TryCast(page.Controls(0), FastColoredTextBox) 
For Each line As String In txt.Lines 
   If line.IndexOf("<vb>", StringComparison.OrdinalIgnoreCase) > 0 Then 
      txt.Language = Language.VB 
      Exit For ' If this is all you have to do exit immediatly
   End If 
Next

编辑: Exit For 允许在不搜索后续不感兴趣的行的情况下中断循环。当然,如果您有其他if,则应删除 Exit For。 另请注意,在我的回答中,您不必为控件中已有的所有字符串创建不必要的数组。 最后一点,既然我们拥有丰富的字符串工具包,为什么还要使用旧式 Instr (VB6)

【讨论】:

  • 感谢您的帮助,不过我有一个问题,如果我在循环中有多个 if 语句,我还应该添加出口吗?我从未使用过 exit for 语句,所以我想知道它的用途。
  • 假设您只对查找脚本语言行感兴趣,我插入了一个 Exit For 以跳出循环。 Exit For 允许在不搜索后续不感兴趣的行的情况下中断循环。当然,如果您有其他 if 则应删除 Exit For。请注意,在我看来,接受的答案存在严重的性能问题。它会创建一个不必要的数组,其中包含您控件中已有的所有字符串。
  • 性能是我的应用程序中的一个大问题,我不能失去任何东西。我使用它的唯一问题是我收到一个错误:字符串类型的值无法转换为 fastcoloredtextboxns.line
  • 你在哪一行得到这个错误?在我的回答中还是在您的问题中?
  • 你在这一行上回答:For Each line As Line In txt.Lines。它在我的身上也不起作用,我应该改变它。
【解决方案2】:

所以我猜你正在使用 CodeProject.com 网站上的 FastColoredTextBox,对吧?

先尝试将文本框的Text拆分成对应的行:

Dim txt As FastColoredTextBox = TryCast(page.Controls(0), FastColoredTextBox)
Dim Lines as string() = txt.Text.Split(VbCrLf)
For Each line As String In txt.Lines
  CBool(InStr(line, "<vb>")) Then
  txt.Language = Language.VB
End If

【讨论】:

  • -1 这会创建控件中已经存在的不必要的字符串数组。此处可以使用 Text 属性。
【解决方案3】:

为什么你要走那么长的路,我现在用以下简短的简单代码做到了:

For i = 0 To Val(TextBox1.Lines.Count)-1
    If TextBox1.Lines(i).ToString.StartsWith("OS Version:") Then
        Label9.Text = TextBox1.Lines(i).ToString
        Exit For
      Exit Sub
    End If
Next

【讨论】:

    猜你喜欢
    • 2021-07-30
    • 2019-02-09
    • 2022-09-30
    • 1970-01-01
    • 1970-01-01
    • 2015-02-09
    • 1970-01-01
    • 2020-03-29
    • 1970-01-01
    相关资源
    最近更新 更多