vb.netdatagridviewdatatablecsvdatagridviewtextboxcell

Correct way of convert delimited texbox lines to a datagridview?


Please give me some guidance about this error. I have a TextBox output with already clean and formatted text delimited by ; which corresponds to 5 columns and unlimited rows. But I don't know how to fill the DataGridView in the right way. I've get this error

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

Sample textbox output 2 lines of 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

Solution

  • You should add the columns once, at the beginning of the app, then use DataGridView.Rows.Add() as suggested by the_lotus. You can simply pass the "holder" array:

    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