vb.net如果行以特定条件开头,则在多行富文本框中进行行编号

时间:2019-03-23 17:29:01

标签: vb.net

首先让我说我对G代码以外的任何一种编码语言都是陌生的,我一直在研究它直到手指受伤为止。实际上,我现在一个人已经在这个项目上工作了一年多,这是我一直找不到的第一个障碍。

我正在为cnc G代码创建一个编辑器,并且试图向其中添加一个Re-number函数。我正在使用多行Richtextbox将G代码显示给用户。我正在尝试编辑以字符“ N”开头的每一行代码,如果某行不是以该字符开头,则将其保留。

我认为最好的方法是通过RTB循环并将每一行传递到一个数组中。然后,我可以使用If语句查看数组中的某个单元格是否以char“ N”或我的情况下“ blockLetter”开头。然后使用替换功能更正行号。

这是我到目前为止所拥有的。

Dim increment As Integer = txtLNIncrement.Text
Dim blockLetter As String = txtLNStartTxt.Text
Dim count As Integer = 0
Dim block As Integer = count + increment 

For Each cell As String In frmNC.NcTextBox.Lines
  If cell.StartsWith(blockLetter) Then
    Dim newCell As String = cell.Replace(blockLetter, block)
    block = block + increment
    MessageBox.Show(newCell)
  End If
Next

需要重新编号的G代码示例: N50 M01 N60 T0101 (TOOL NAME) N70 M41 N80 G96 S350 N90 M03 N100 M08

这就是我想要的: N10 M01 N20 T0101 (TOOL NAME) N30 M41 N40 G96 S350 N50 M03 N60 M08

这是我在运行上面的代码时得到的: 1050 M01 2060 T0101 (TOOL NAME) 3070 M41 4080 G96 S350 5090 M03 60100 M08

我相信我的问题是cell.replace是将每个单元格拆分为“ N”字符,并将其全部放在一起。因此,我要在现有数字前面看到的内容减去“ N”字符。如何将现有的程序段号覆盖为正确的升序程序段号,并保留“ N”字符?我是按照正确的方式进行操作还是有更好的方法?任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

尝试这样的事情:

Private increment As Integer = 10
Private blockLetter As String = "N"

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim newLine As String
    Dim values() As String
    Dim lineNumber As Integer = 0
    Dim lines As New List(Of String)(NcTextBox.Lines)
    For i As Integer = 0 To lines.Count - 1
        If lines(i).TrimStart().StartsWith(blockLetter) Then
            values = lines(i).TrimStart(" " & blockLetter.ToCharArray).Split(" ")
            lineNumber = lineNumber + increment
            values(0) = lineNumber
            newLine = blockLetter & String.Join(" ", values)
            lines(i) = newLine
        End If
    Next
    NcTextBox.Lines = lines.ToArray
End Sub

答案 1 :(得分:0)

这很简单:

Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
     Dim blockLetter As String = "N"
    Dim increment As Integer = 1
    For i As Integer = 0 To RichTextBox1.Lines.Length - 1 Step 1
        Dim fullLine As String = RichTextBox1.Lines(i)

        If fullLine.StartsWith(blockLetter) Then
            Dim numbering As String = fullLine.Remove(RichTextBox1.Lines(i).IndexOf(" "))
            Dim block As Integer = numbering.Substring(1)
            Dim newCell As String = blockLetter & block + increment
            MessageBox.Show(newCell)
        End If
    Next

End Sub

结果:

  

Label1.Text将随着按钮单击而增加。

这都是关于Substring()的,它从'N'之后的索引1开始,因此您将获得该数字。

祝您编码顺利!