Nejthe
Nejthe

Reputation: 580

Adding numbers in TextBox

I have this code that it works only if all the textBox contains values.. But if a textbox is empty 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 that it must be a function like IsNull but for the integer values.. Does anyone know what it is ?

Upvotes: 3

Views: 528

Answers (5)

8bitcat
8bitcat

Reputation: 2224

You can't parse an empty string "". Check if the box contains anything before parsing.

Textbox.text != ""

Other answers are quicker to use tryparse is the best in fact, as it does the same with less lines of code!

Upvotes: 1

Brad Christie
Brad Christie

Reputation: 101604

You're looking for Int32.TryParse:

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

Which you call on every .Text property, then add them together. You can also make an extension to make it easier (if you chose):

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

Upvotes: 8

Sean Airey
Sean Airey

Reputation: 6372

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 fails, it will set the variable to 0.

You can also inline some of the 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 reference: http://msdn.microsoft.com/en-us/library/f02979c7.aspx

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

Upvotes: 2

Soner Gönül
Soner Gönül

Reputation: 98740

Int32 is a value type. It can't be null. Or course there is a nullable types but hey..

Try with Int32.Tryparse() method.

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

Int32.TryParse(txtChild1.Text, out val)

returns boolean true if s was converted successfully; otherwise, false.

Upvotes: 1

Massimiliano Peluso
Massimiliano Peluso

Reputation: 26727

you should check if the TextBox is not empty before parsing it or you can use TryParse

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

Upvotes: 2

Related Questions