You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从文本提取关节坐标至DataGridView为空问题排查求助

问题:提取关节坐标到DataGridView为空的排查与修复

我尝试从文本文件中提取关节坐标并展示到DataGridView中,但运行代码后DataGridView始终为空。

空DataGridView截图

原代码

Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
        Dim filePath As String = OpenFileDialog1.FileName
        Dim lineNumber As Integer = -1
        Dim searchString As String = "TABLE: ""JOINT COORDINATES"""

        ' Check if file exists
        If Not File.Exists(filePath) Then
            MessageBox.Show("File not found")
            Return
        End If

        ' Read the file content
        Dim fileContent As String = File.ReadAllText(filePath)

        ' Open the file for reading
        Using fileStream As New FileStream(filePath, FileMode.Open, FileAccess.Read)
            Using streamReader As New StreamReader(fileStream)
                Dim data() As String = fileContent.Split({Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)

                ' Loop through each line in the file
                Dim line As String
                Do
                    lineNumber += 1
                    line = streamReader.ReadLine()
                    If line IsNot Nothing AndAlso line.Contains(searchString) Then
                        Exit Do
                    End If
                Loop Until line Is Nothing

                ' Parse the data and add to DataGridView
                Dim dataGrid As New DataGridView()
                With dataGrid
                    .ColumnCount = 2
                    .Columns(0).Name = "Joint"
                    .Columns(1).Name = "Coordinate"

                    Dim startIndex As Integer = lineNumber + 1
                    While startIndex < data.Length AndAlso data(startIndex).Contains("Joint=")
                        ' Parse the data
                        Dim jointStr As String = data(startIndex).Substring(data(startIndex).IndexOf("Joint=") + 6, data(startIndex).IndexOf(" ") - (data(startIndex).IndexOf("Joint=") + 6))
                        Dim x As Integer = Integer.Parse(data(startIndex).Substring(data(startIndex).IndexOf("XorR=") + 5, data(startIndex).IndexOf("Y=") - (data(startIndex).IndexOf("XorR=") + 5)).Trim())
                        Dim y As Integer = Integer.Parse(data(startIndex).Substring(data(startIndex).IndexOf("Y=") + 2, data(startIndex).IndexOf("Z=") - (data(startIndex).IndexOf("Y=") + 2)).Trim())
                        Dim z As Integer = Integer.Parse(data(startIndex).Substring(data(startIndex).IndexOf("Z=") + 2, 3).Trim())

                        ' Add the data to DataGridView
                        Dim jointCoordStr As String = "(" & x & "," & y & "," & z & ")"
                        .Rows.Add(jointStr, jointCoordStr)

                        startIndex += 1
                    End While
                End With

                ' Show the DataGridView
                Dim form As New Form()
                With form
                    .Controls.Add(dataGrid)
                    .ShowDialog()
                End With
            End Using
        End Using
    End Sub

预期输出

期望的DataGridView输出样式:

JointCoordinate
10,1,0
20,1,10.93
30,11,0
......

预期DataGridView输出截图


问题排查与修复

原代码存在几个关键问题导致DataGridView为空:

  • 文件读取逻辑冲突:同时使用File.ReadAllText和StreamReader读取文件,导致行号计数与数组索引不匹配,无法定位到目标数据行。
  • 坐标解析错误:用Integer.Parse处理含小数的坐标会抛出异常,且Z坐标截取使用固定长度3,适配性差。
  • 字符串截取脆弱:依赖固定空格位置分割数据,行格式变化就会导致截取失败。

修复后的代码

Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
    Dim filePath As String = OpenFileDialog1.FileName
    Dim searchString As String = "TABLE: ""JOINT COORDINATES"""

    If Not File.Exists(filePath) Then
        MessageBox.Show("File not found")
        Return
    End If

    ' 一次性读取所有非空行,避免指针冲突
    Dim allLines As String() = File.ReadAllLines(filePath).Where(Function(l) Not String.IsNullOrWhiteSpace(l)).ToArray()
    Dim startParsingIndex As Integer = -1

    ' 定位到目标表的起始行
    For i As Integer = 0 To allLines.Length - 1
        If allLines(i).Contains(searchString) Then
            startParsingIndex = i + 1
            Exit For
        End If
    Next

    If startParsingIndex = -1 Then
        MessageBox.Show("Joint coordinates table not found")
        Return
    End If

    Dim dataGrid As New DataGridView()
    With dataGrid
        .ColumnCount = 2
        .Columns(0).Name = "Joint"
        .Columns(1).Name = "Coordinate"
        .Dock = DockStyle.Fill ' 设置Dock属性让表格填满窗口
    End With

    ' 解析关节数据行
    For i As Integer = startParsingIndex To allLines.Length - 1
        Dim line As String = allLines(i)
        If Not line.Contains("Joint=") Then
            Exit For ' 遇到非关节行就停止解析
        End If

        ' 使用正则表达式更稳定地提取数据
        Dim jointMatch = System.Text.RegularExpressions.Regex.Match(line, "Joint=(\d+)")
        Dim xMatch = System.Text.RegularExpressions.Regex.Match(line, "XorR=([\d.]+)")
        Dim yMatch = System.Text.RegularExpressions.Regex.Match(line, "Y=([\d.]+)")
        Dim zMatch = System.Text.RegularExpressions.Regex.Match(line, "Z=([\d.]+)")

        If jointMatch.Success AndAlso xMatch.Success AndAlso yMatch.Success AndAlso zMatch.Success Then
            Dim jointNum As String = jointMatch.Groups(1).Value
            Dim coordStr As String = $"{xMatch.Groups(1).Value},{yMatch.Groups(1).Value},{zMatch.Groups(1).Value}"
            dataGrid.Rows.Add(jointNum, coordStr)
        End If
    Next

    ' 显示表格窗口
    Dim form As New Form()
    form.Size = New Size(400, 600)
    form.Controls.Add(dataGrid)
    form.ShowDialog()
End Sub

修复说明

  1. 改用File.ReadAllLines一次性读取所有非空行,确保行索引准确,避免文件指针冲突。
  2. 使用正则表达式提取数据,比硬编码的Substring更稳定,适配不同格式的行内容。
  3. 保留坐标的原始字符串格式,避免整数转换丢失小数信息。
  4. 给DataGridView设置Dock = DockStyle.Fill,确保表格在窗口中正常显示。
  5. 添加未找到目标表的提示,增强容错性。

内容的提问来源于stack exchange,提问作者Ahmad Riyanto

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 18:33:15