Adding numbers to TextBox

I have this code that only works if the entire text block contains values. But if the textbox is empty then I get an error.

Int32 Total = Int32.Parse((txtChild1.Text))
            + Int32.Parse(txtChild2.Text)
            + Int32.Parse(txtChild3.Text)
            + Int32.Parse(txtWife1.Text)
            + Int32.Parse(txtWife2.Text)
            + Int32.Parse(txtWife3.Text);

      

I know it should be a function of type IsNull, but for integer values. Does anyone know what this is?

+3


source to share


5 answers


You can use Int32.TryParse

:

Int32 int1 = 0;
Int32.TryParse(txtChild1.Text, out int1);
//.... more int declarations
Int32 total = int1 + int2 + int3; //etc. etc.

      

TryParse

will try to parse the text and if it doesn't work it will set the variable to 0.

You can also inline some logic (although this makes the code very long and messy):



Int32 Total = (txtChild1.Text.Length == 0 ? 0 : Int32.TryParse(txtChild1.Text)) + (txtChild2.Text.Length == 0 ? 0 : Int32.TryParse(txtChild2.Text)); //etc. etc.

      

Int32.TryParse

link: http://msdn.microsoft.com/en-us/library/f02979c7.aspx

Shorthand if link: http://msdn.microsoft.com/en-gb/library/ty67wk28(v=vs.110).aspx

+2


source


You are looking for Int32.TryParse

:

Int32 val;
if (Int32.TryParse(txtChild1.Text, out val)){
  // val is a valid integer.
}

      

You call each property .Text

and then add them together. You can also make an extension to make it easier (if you choose):

public static class NumericParsingExtender
{
    public static Int32 ToInt32(this String input, Int32 defaultValue = 0)
    {
      if (String.IsNullOrEmpty(input)) return defaultValue;
      Int32 val;
      return Int32.TryParse(input, out val) ? val : defaultValue;
    }
}

      



Then in practice:

Int32 total = txtChild1.Text.ToInt32() + txtChild2.Text.ToInt32()
            + txtChild3.Text.ToInt32() + /* ... */;

      

And of course an example

+8


source


you should check if it is not worth it TextBox

before parsing it or you can useTryParse

http://msdn.microsoft.com/en-us/library/f02979c7.aspx

+2


source


You cannot parse the empty string "". Check if the field contains nothing before parsing.

Textbox.text != ""

      

The other answers are faster using tryparse is actually better as it does the same thing with fewer lines of code!

+1


source


Int32

- value type. It can't be null

. Or, of course, there is nullable types

but hey ..

Try with Int32.Tryparse()

.

Converts the string representation of a number to its 32-bit signed integer equivalent. The return value indicates whether the operation was successful.

Int32.TryParse(txtChild1.Text, out val)

      

returns boolean

true

if s was successfully converted; otherwise false

.

+1


source







All Articles