Convert String to integer and get null equal to 0

11,849

Solution 1

You have to detect one by one. Better way, will be to create your own function. Try below.

Dim count1 As Integer = 0
count1 = ConvertToInteger(a.Text) + ConvertToInteger(b.Text) + ConvertToInteger(c.Text)
txt_display.Text = count1




Private Function ConvertToInteger(ByRef value As String) As Integer
    If String.IsNullOrEmpty(value) Then
        value = "0"
    End If
    Return Convert.ToInt32(value)
End Function

Solution 2

If your objective is to sum the values in your textboxes and ignore the textboxes that cannot be converted to integers then you can simply use Int32.TryParse.
It will set your variable to 0 if the text cannot be converted to an integer without throwing exceptions.

' In place of your textboxes
Dim x1 As String = "2"
Dim x2 As String = Nothing
Dim x3 As String = "5"

Dim a, b, c As Integer

Int32.TryParse(x1, a)
Int32.TryParse(x2, b)
Int32.TryParse(x3, c)

Dim result = a + b + c
Console.WriteLine(result)

Instead, if you want to write the "0" string into the textbox text to signal your user of the wrong input, then you have to check the textboxes one by one, again using Int32.TryParse

Dim value1 as Integer
if Not Int32.TryParse(a.Text, value1) Then
   a.Text = "0"
End If

' Here the variable value1 contains the converted value or zero.
' repeat for the other textboxes involved

Solution 3

A different approach using If Operator:

Dim count1 As Integer = 0
count1 = If(String.IsNullOrEmpty(a.Text), 0, Convert.ToInt32(a.Text)) + If(String.IsNullOrEmpty(b.Text), 0, Convert.ToInt32(b.Text)) + If(String.IsNullOrEmpty(c.Text), 0, Convert.ToInt32(c.Text))
txt_display.Text = count1

Solution 4

Example:

If String.IsNullOrEmpty(a.Text) Then
 a.Text = "0"
End If
Share:
11,849
Admin
Author by

Admin

Updated on June 15, 2022

Comments

  • Admin
    Admin about 2 years

    May I know got any simple way to perform this? It will hit an error when a.text is null. If I don't detect one by one, With a simple code may I convert a.text null to 0?

    Dim count1 As Integer = 0
    count1 = Convert.ToInt32(a.Text) + Convert.ToInt32(b.Text) + Convert.ToInt32(c.Text)
    txt_display.Text = count1
    

    Got any other method rather that I do like below detect one by one.

    if a.Text = "" Then
    a.Text = 0
    End If