Question How to skip/ignore or bypass empty Text boxes while calculating ?

aksl

Member
Joined
Jan 31, 2014
Messages
11
Programming Experience
Beginner
i am developing a simple marks grading system using vb.net in visual studio 2013. my code is this.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
       If TextBox1.Text >= 0 And TextBox1.Text = 51 And TextBox1.Text = 0 And TextBox2.Text = 51 And TextBox2.Text = 0 And TextBox3.Text = 51 And TextBox3.Text
 

JuggaloBrotha

VB.NET Forum Moderator
Staff member
Joined
Jun 3, 2004
Messages
4,524
Location
Lansing, MI; USA
Programming Experience
10+
I would look into the TryParse method for either Integer or Decimal depending on whether the values in the textboxes have decimal digits, if the TextBox is left blank you can use a string "0" in as it's value when trying to convert to the numeric type. Then just add them up together or whatever using the numeric variable at that point.
Also a good idea is to use the NumericUpDown control on your form(s) when you want to collect numbers only, it has a Value property (of type Decimal) already so you can forgo the string to numeric conversion.
 

jmcilhinney

VB.NET Forum Moderator
Staff member
Joined
Aug 17, 2004
Messages
14,319
Location
Sydney, Australia
Programming Experience
10+
It's hard to know exactly what "calculation" you're trying to perform based on that code but here are some examples that might help.
Dim allTextBoxes = Me.Controls.OfType(Of TextBox)()

Dim total = allTextBoxes.Sum(Function(tb)
                                 Dim number As Integer

                                 Integer.TryParse(tb.Text, number)

                                 'number will contain the numerical value of the Text or zero if it was not a number.
                                 Return number
                             End Function)

If allTextBoxes.All(Function(tb)
                        Dim number As Integer

                        Return Integer.TryParse(tb.Text, number) AndAlso number > 50
                    End Function) Then
    'All TextBoxes contain a number greater than 50.
End If

If allTextBoxes.Any(Function(tb)
                        Dim number As Integer

                        Return tb.TextLength > 0 AndAlso Not Integer.TryParse(tb.Text, number)
                    End Function) Then
    'At least one TextBox is not empty and contains a non-numerical value.
End If
 
Top Bottom