Anu Anu - 3 months ago 56
Vb.net Question

Dynamically add multiple rows in datagridview in vb.net

Im reading cell values from excel sheet and add it in datagridview.
I followed below code but it add only one row and it is the last row in excel sheet. I have four rows in excel sheet so datagridview also should have four rows.

For x = 9 To xlWorkSheet.UsedRange.Rows.Count
For j = 0 To LogCalcEnter.ColumnCount - 1
If Not String.IsNullOrEmpty(xlWorkSheet.Cells(1 + x, j + 1).Value) Then
LogCalcEnter.Rows.Add()
LogCalcEnter.Item(j, 0).Value = xlWorkSheet.Cells(1 + x, j + 1).value
End If
Next
Next


LogCalcEnter is name of the Datagridview

Answer

You add a new row for every column that you are looping over. The code below creates a new row for each row you loop over. I changed LogCalcEnter.Item(j, 0) to LogCalcEnter.Item(j, rowIndex) so that you're filling out the row information too. Note: I haven't actually run it, you may have issues with the indices you are using in this. You say you have 4 rows in the spreadsheet but you started with x = 9. Also the +1's in xlWorkSheet.Cells(1 + x, j + 1).Value) push the row count over the amount in UsedRange.

    For x = 1 To xlWorkSheet.UsedRange.Rows.Count
        Dim rowIndex = LogCalcEnter.Rows.Add()
        Dim hasValue = False
        For j = 0 To LogCalcEnter.ColumnCount - 1
            If Not String.IsNullOrEmpty(xlWorkSheet.Cells(1 + x, j + 1).Value) Then
                hasValue = True
                LogCalcEnter.Item(j, rowIndex).Value = xlWorkSheet.Cells(1 + x, j + 1).value
            End If
        Next
        If Not hasValue Then LogCalEnter.Rows.RemoveAt(rowIndex)
    Next
Comments