将带分隔符的文本框行转换为数据网格视图的正确方法?

Correct way of convert delimited texbox lines to a datagridview?

请给我一些关于这个错误的指导。我有一个 TextBox 输出,其中已经干净且格式化的文本由 ; 分隔,对应于 5 列和无限行。但是我不知道如何以正确的方式填写 DataGridView 。我收到此错误

Index was out of range. Must be non- negative and less than the size of the collection. Parameter name : index

示例文本框输出 2 行 44

4C5E0C4255CD;pppoe;4C:5E:0C:42:55:CD;192.168.29.71;2d19h16m6s 4C5E0C458887;pppoe;4C:5E:0C:45:88:87;192.168.29.110;2d19h16m3s

Private Sub QueryMkt_Click(sender As Object, e As EventArgs) Handles QueryMkt.Click
    DataGridView1.AutoGenerateColumns = False
    DataGridView1.Columns.Add("name", "name")
    DataGridView1.Columns.Add("service", "service")
    DataGridView1.Columns.Add("caller-id", "caller-id")
    DataGridView1.Columns.Add("address", "address")
    DataGridView1.Columns.Add("uptime", "uptime")

    For i As Integer = 0 To tbOutput.Lines.Length - 2

        Dim delimitedText As String = tbOutput.Lines(i)
        Dim holder As String() = Regex.Split(delimitedText, ";")

        'MessageBox.Show((i), (holder(0) + holder(4)))
        'DataGridView1.Item(0, i).Value = holder(0).ToString()

        DataGridView1.Rows(i).Cells("name").Value = holder(0).ToString()
        DataGridView1.Rows(i).Cells("service").Value = holder(1).ToString()
        DataGridView1.Rows(i).Cells("caller-id").Value = holder(2).ToString()
        DataGridView1.Rows(i).Cells("address").Value = holder(3).ToString()
        DataGridView1.Rows(i).Cells("uptime").Value = holder(4).ToString()
    Next
End Sub

您应该在应用程序的开头添加一次列,然后按照 the_lotus 的建议使用 DataGridView.Rows.Add()。您可以简单地传递 "holder" 数组:

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    DataGridView1.AutoGenerateColumns = False
    DataGridView1.Columns.Add("name", "name")
    DataGridView1.Columns.Add("service", "service")
    DataGridView1.Columns.Add("caller-id", "caller-id")
    DataGridView1.Columns.Add("address", "address")
    DataGridView1.Columns.Add("uptime", "uptime")
End Sub

Private Sub QueryMkt_Click(sender As Object, e As EventArgs) Handles QueryMkt.Click
    For i As Integer = 0 To tbOutput.Lines.Length - 2
        Dim delimitedText As String = tbOutput.Lines(i)
        Dim holder As String() = Regex.Split(delimitedText, ";")
        DataGridView1.Rows.Add(holder)
    Next
End Sub