Hi all, I'm fairly new to VB. I'm working on a Windows forms app that will average a set of numbers, the only catch is that there are 10 textboxes(4 in the example for times sake), and not all of the textboxes could be filled with a number...

I know that if i had a given set of numbers:

Dim a, b, c, d As Integer
        a = t1.Text
        b = t2.Text
        c = t3.Text
        d = t4.Text
        avg.Text = (Val(a) + Val(b) + Val(c) + Val(d)) / 4

but what if only 3 of the textboxes have numbers entered, how can I have vb find out how many textboxes have values entered into them, then use that number to divide by?

I've been trying something like this, I think i'm on the right track:

Dim i As Integer
        Dim xCount As Integer
        For i = 1 To xCount
            For Each c As Control In Me.Controls
                If TypeOf c Is TextBox Then
                    If c.Text > "0" Then
                        xCount = xCount + 1
                    End If
                End If
            Next
        Next i
        label1.text = xCount

the four text boxes (tA, tB, tC, tD)

one button (cmdCalculate)

and one more text box with a name that doesn't start with "t" (OutputTxtAvg)

Private Sub cmdCalculate_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdCalculate.Click

        Dim iNumeratorCnt As Integer = 0
        Dim iSum As Integer = 0

        For Each ctrl As Control In Me.Controls
            If ctrl.Name.StartsWith("t") Then
                Dim tmpText As New TextBox
                tmpText = DirectCast(ctrl, TextBox)
                If tmpText.Text.Length > 0 Then
                    Try
                        iSum += Val(tmpText.Text)
                        iNumeratorCnt += 1


                    Catch ex As Exception
                        MessageBox.Show("Please enter valid integers", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
                    End Try
                End If

            End If
        Next
        If iNumeratorCnt > 0 Then
            OutputtxtAvg.Text = Convert.ToDouble(iSum / iNumeratorCnt)
        End If

    End Sub

That worked just beautifully, thank you.

I see how that can be used with as many textboxes as I want as well. I've never seen the "If ctrl.name.startswith()" used like that before, I can see where that will come in handy.

Thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.