James Kurd
James Kurd

Reputation: 57

ISNUMERIC AND EMPTY STRING

I want to create an application where if someone enters a number, it is entered into a listbox but if someone enters an alphabet or leave the textbox blank, a message box should appear. How to do this? Thanks.

  Private Sub btnRecord_Click(sender As Object, e As EventArgs) Handles btnRecord.Click
            Dim grade As Double
            grade = CDbl(txtGrades.Text)
            If grade >= 0 And IsNumeric(grade) = True Then

                lstGrades.Items.Add(grade)
                txtGrades.Text = " "

            ElseIf txtGrades.Text = " " Then
                MessageBox.Show("Number cannot be less than 0", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning)

            ElseIf IsNumeric(txtGrades.Text) = False Then
                MessageBox.Show("Number cannot be an alphabet", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning)
            End If
  End Sub

Upvotes: 0

Views: 677

Answers (1)

Brian M Stafford
Brian M Stafford

Reputation: 8868

You could simplify your logic and eliminate errors by using TryParse. This method determines if a String can be converted to a Double and returns either True or False along with the converted value:

   Private Sub btnRecord_Click(sender As Object, e As EventArgs) Handles btnRecord.Click
      Dim grade As Double

      If Double.TryParse(txtGrades.Text, grade) Then
         lstGrades.Items.Add(grade)
         txtGrades.Text = " "
      Else
         MessageBox.Show("Number cannot be an alphabet", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning)
      End If
   End Sub

Upvotes: 1

Related Questions