Search code examples
vb.netdatagridviewservice-reference

Datagridview is blank - trying to populate from API service reference


I have been all over the net today trying different things, but I am just missing the boat somehow. I am trying to populate a datagridview with data from a supplied api. However, when the code executes, no errors are thrown, but no information is displayed within the datagridview. You will also notice a listbox referenced. I am able to display values from the API within the listbox as expected, so I know I am just doing something wrong with the datagridview setup, but I just can't seem to pinpoint it. Thanks for any help!

  Dim frmTestCase As New Form1

    Dim dgv As New DataGridView

    dgv = frmTestCase.DataGridView1

    dgv.Columns.Add("ID", "ID")
    dgv.Columns.Add("Name", "Name")

    Dim i As Integer

    'Loop through test cases and get their data for datagrid
    For i = 0 To UBound(remoteTestCases) - 1
        Dim matchingTestCase = remoteTestCases(i)
        Dim testCaseID As String = CStr(matchingTestCase.TestCaseId.Value)
        Dim testCaseName As String = matchingTestCase.Name

        Dim row As DataGridViewRow = New DataGridViewRow

        row.CreateCells(dgv)

        row.Cells(0).Value = testCaseID
        row.Cells(1).Value = testCaseName

        dgv.Rows.Add(row)


        Me.ListBox1.Items.Add(testCaseID)

    Next

Solution

  • This code:

    Dim frmTestCase As New Form1
    Dim dgv As New DataGridView
    dgv = frmTestCase.DataGridView1
    

    appears to be trying to shorten the reference to dgv. But in so doing, it creates a new Form1 instance and by extension a new DataGridView1. You could well be populating a DGV on a form that is never shown.

    One remedy would be to rename DataGridView1 on this form (Me) to something more meaningful or shorter using the IDE Property Editor.

    IF the dgv is on the current form, the way to create a shorter reference is:

    Dim dgv As DataGridView = Me.DataGridView1
    

    If the control is on a different existing form1:

    Dim dgv As DataGridView = theOtherFrmRef.DataGridView1
    

    Finally, if you are trying to populate the DGV on a new form instance, be sure to Show() it at the end.

    New creates a new instance of whatever and you do not need a new Form ref or a new DGV at all. Assuming there are columns already added to the DGV, adding rows can also be simplified to:

    dgv.Rows.Add(testCaseID, testCaseName)
    

    1 Also assumes explicit form instances. Otherwise you might not be posting to the instance you think you are.