MadsTheMan
MadsTheMan

Reputation: 703

How can I simplify and enhance multiple if-statements usage?

So I'm just curious and trying to improve my current application. Couldn't really find any examples of this.

I've got a bunch of checkboxes cbcin my form and I want to do something if none of them is checked.

Is there any better ways to do this?

      If Not cbc1.Checked = True Then
        If Not cbc2.Checked = True Then
            If Not cbc3.Checked = True Then
                If Not cbc4.Checked = True Then
                    If Not cbc5.Checked = True Then
                        If Not cbc6.Checked = True Then
                            If Not cbc7.Checked = True Then
                                If Not cbc8.Checked = True Then
                                    If Not cbc9.Checked = True Then

                                        'Do this and that

                                    End If
                                End If
                            End If
                        End If
                    End If
                End If
            End If
        End If
    End If

I find this a bit messy and its probably not a good way to write a good code.

Upvotes: 1

Views: 262

Answers (2)

jack3694078
jack3694078

Reputation: 1033

Why not use .All() from LINQ? It's cool (and readable)

Dim checkBoxes As New List(Of CheckBox) From {cbc1,cbc2,cbc3} 'all your check boxes
If checkBoxes.All(Function(cb) Not cb.Checked) Then
    'Do this and that
End If

Also you don't need to do if boolObj = True Then. Just if boolObj Then is fine.

Edit: The condition was the other way round. Fixed now.

Upvotes: 3

Ankit Ranjan
Ankit Ranjan

Reputation: 13

Since you aren't doing anything, except in your last If statement, why not use AND operator and combine all the boolean checks ? That way you will only have one if then end if loop.

Upvotes: 0

Related Questions