Home > Net >  create function for sender object handler
create function for sender object handler

Time:01-03

how do i create a function for a sender as object click? I tried something, but it didn't work out.

 Private Function functionName(ByVal sender As Object, e As EventArgs)

        If sender.checked = True Then
            For i As Integer = 2 To 14
                If i <> 2 Then
                    Dim cbClubs = DirectCast(Controls.Item("cbBtt" & i & "detrefla"), CheckBox) 'Clubs
                    cbClubs.Checked = False
                End If
            Next
        End If

    End Function

   Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        functionName(cbBtt2detrefla, sender)
    End Sub

CodePudding user response:

Let's put some order in this code.

Private Function functionName(ByVal sender As Object, e As EventArgs)
   '...
End Function

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    functionName(cbBtt2detrefla, sender)
End Sub

Why are you using e As EventArgs in functionName(...) declaration? It's never used, so u can delete it:

Private Function functionName(ByVal sender As Object)

In functionName you are evaluating sender.Checked (a tip: you can use If sender.Checked instead of If sender.Checked = True): why not to define sender as CheckBox, instead of Object?

Private Function functionName(ByVal sender As CheckBox)

Now, let's see the for Loop:

For i As Integer = 2 To 14
    If i <> 2 Then
        '...
    End If
Next

You are evaluating i from 2 to 14, but you don't want to do anything if i = 2. Why not to start the for loop from i=3? It's faster and better.

For i As Integer = 3 To 14
    '...
Next

Another thing: functionName() doesn't produce an output, so it should be a Sub, not a Function.

Now, your code is:

Private Sub functionName(ByVal sender As CheckBox)
    If sender.Checked Then
        For i As Integer = 3 To 14
            '...
        Next
    End If
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    functionName(cbBtt2detrefla)
End Sub

Furthermore, if functionName is called only by Button1_Click and here it is only used with cbBtt2detrefla, you can avoid separating the two subs:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click    
    If cbBtt2detrefla.Checked Then
        For i As Integer = 3 To 14
            '...
        Next
    End If
End Sub

Last, but not least:

Dim cbClubs = DirectCast(Controls.Item("cbBtt" & i & "detrefla"), CheckBox) 'Clubs
cbClubs.Checked = False

This works only if cbBtt3detrefla and the others checkBoxes are directly on the form. If they are in a Panel, for example, you'll get a System.NullReferenceException. If you want to iterate on every control, you can do something like this.

  • Related