How do you change a procedure so that multiple controls/objects can use the same code?

Cynolycus 260 Reputation points
2023-04-21T11:04:09.18+00:00

I have tried looking for this answer and I know there is an example somewhere because I've seen it before, but now that I want to look at it I just can't find it. For most this is a simple thing to do. All I wanted to know is how do you change a sub so that it works for multiple objects. Just for this question I put this simple sub together, it has no real purpose. This was originally the DGV1s RowValidating, I just changed the name of the sub and then had to add the "Dim DGV As DataGridView = DGV1" so that it would work for DGV1. Now how do you get it to work so that either DGV1 or DGV2 can use it, as this only works for the DGV specified in the dim statement?


   Private Sub RowValidating(sender As Object, e As DataGridViewCellCancelEventArgs) Handles DGV1.RowValidating, DGV2.RowValidating
        Dim DGV As DataGridView = DGV1
        Dim EmptyCount As Integer
        For i = 1 To DGV.ColumnCount - 1
            If DGV.Rows(DGV.CurrentRow.Index).Cells(i).EditedFormattedValue.ToString = "" Then
                EmptyCount += 1
            End If
        Next
        TextBoxCount.Text += DGV.Name & " row " & DGV1.CurrentRow.Index + 1 & " has " & EmptyCount & " empty cells." & vbCrLf
    End Sub

Developer technologies | VB
0 comments No comments
{count} votes

Accepted answer
  1. Dewayne Basnett 1,381 Reputation points
    2023-04-21T13:16:45.4566667+00:00

    By using the Sender you can handle as many as you want,

        Private Sub RowValidating(sender As Object,
                                  e As DataGridViewCellCancelEventArgs) Handles DGV1.RowValidating, DGV2.RowValidating
            Dim DGV As DataGridView = DirectCast(sender, DataGridView) '<<<<<<<<<<<<<<
            Dim EmptyCount As Integer
            For i = 1 To DGV.ColumnCount - 1
                If DGV.Rows(DGV.CurrentRow.Index).Cells(i).EditedFormattedValue.ToString = "" Then
                    EmptyCount += 1
                End If
            Next
            TextBoxCount.Text += DGV.Name & " row " & DGV1.CurrentRow.Index + 1 & " has " & EmptyCount & " empty cells." & vbCrLf
        End Sub
    
    
    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.