将分隔的文本框行转换为datagridview的正确方法?

时间:2015-02-09 15:11:02

标签: vb.net datagridview datatable delimited-text datagridviewtextboxcell

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

  

指数超出范围。必须是非负数且小于集合的大小。参数名称: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

1 个答案:

答案 0 :(得分:0)

您应该在应用的开头添加一次列,然后按照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