Thanapipat Pacharatanakoson Thanapipat Pacharatanakoson - 3 months ago 23
Vb.net Question

How can i build function that can receive DatagridView.Rows or Datagridview.SelectedRows?

The function must support two case
first case, it can receive All rows in the datagridview.
and Second case, It can receive only selected rows.

If Case_A Then

PrintLabel(dtg.SelectedRows)
End If

If Case_B Then
PrintLabel(dtg.Rows)
End If


Function PrinLabel may be something like these

Public Function PrintLabel(ByVal dtgvNeedPrint As DataGridViewRowCollection) As Boolean

For Each dtgRow As DataGridViewRow In dtgvNeedPrint
''// Do something.
End

End Function


But it's error.Because of dtg.SelectedRows isn't DataGridViewRowCollection. Type isn't matches.

Answer

You can't use either type as neither inherits the other. Instead, declare your parameter as type IEnumerable(Of DataGridViewRow) and then you can call Cast(Of DataGridViewRow) on either collection and pass the result to your method. An IEnumerable is all you need anyway, if what you intend to do is loop over the list with a For Each loop.

Public Function PrintLabel(rows As IEnumerable(Of DataGridViewRow)) As Boolean
    For Each row In rows
        '' Do something.
    End
End Function


If Case_A Then
    PrintLabel(dtg.SelectedRows.Cast(Of DataGridViewRow)())
End If

If Case_B Then
    PrintLabel(dtg.Rows.Cast(Of DataGridViewRow)())
End If