locked
Help adding datagridview row RRS feed

  • Question

  • I am trying to read a text file (csv) and add each row to a datagridview control, i have this code

    Private Sub btnImportContact_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnImportContact.Click

    MessageBox.Show("File should be CSV with no quotes in following format: name,emailaddress,faxnumber,sendemail,sendfax")

    ofd1.ShowDialog()
    Dim fname As String = ofd1.FileName
    Dim sr As System.IO.StreamReader = System.IO.File.OpenText(fname)
    Do Until sr.Peek = -1
    Dim line As String = sr.ReadLine()
    Dim arrItems() As String = Split(line, ",")
    Dim dgrow As New DataGridViewRow
    Dim dgcell(5) As DataGridViewCell
    Dim a As Integer
    Dim b As Integer = arrItems.Length
    For a = 0 To b
    dgcell(a).Value = arrItems(a)
    dgrow.Cells.Add(dgcell(a))
    Next
    dgAddContacts.Rows.Add(dgrow)
    Loop
    End Sub

    My text file is as follows

    test1,test@bentest.com,01422556665,1,1
    test2,blah@somewhere.com,01152212211,1,1
    testing3,sdfsadf@dfdf.com,445652254,1,1
    test4,test@benddtest.com,01dd422556665,1,1
    test5,ssdasd@sds.com,87897979,1,1

    The code throws an exception "object not set to instance of an object" on the line

    dgcell(a).Value = arrItems(a)

    However I wont let me dim the dgcell using new keyword "arrays cannot be declared with new", even taking the array out it says "new cannot be used on a class that mustinherit"

    Can anyone help? Thanks.

    Sunday, July 17, 2005 10:34 PM

Answers

  • Hi,


    I guess the best method on adding rows in a datagridview is to create a datatable, set it as its datasource and additems in the datatable. Here's a pseudo-code:


    Dim dt As New DataTable

    dt.Columns.Add(<Add column parameters>)
    dgridView.DataSource = dt
    ' Add new row
    Dim dr as DataRow = dt.NewRow()
    dr("Col1") = "myValue"
    dt.Rows.Add(dr)




    cheers,


    Paul June A. Domag
    Monday, July 18, 2005 1:17 AM