-1

I am getting the above error from the following code

System.Collections.Generic.List<int> ListSms = new System.Collections.Generic.List<int>();
ListSms.Add(int.Parse(sms.Sms_Nom));

the problem looks like some space include in the text i brought in Sms_Nom so this why I try to Parse it but it dosen't work !

any ideas ? thanx

huMpty duMpty
  • 14,346
  • 14
  • 60
  • 99
JHDesigne
  • 3
  • 5
  • 1
    "so this why I try to Parse it" - what made you think that `int.Parse` would accept values with spaces? You need to get it into the right format *before* you parse it. – Jon Skeet May 22 '14 at 09:55
  • 2
    The parse failed. The value contained in `sms.Sms_Nom` could not be parsed to an `int`. How should we know why without seeing the value of `sms.Sms_Nom`? Use a debugger to find it. – Cody Gray - on strike May 22 '14 at 09:55

3 Answers3

1
int value = 0;
if (int.TryParse(sms.Sms_Nom, out value))
{
  ListSms.Add(value);              
}

Have a look at this question about Parse v. TryParse

Update - to remove spaces in beteween

 if (int.TryParse(sms.Sms_Nom.ToCharArray()
             .Where(c => !Char.IsWhiteSpace(c))
             .Select(c => c.ToString())
             .Aggregate((a, b) => a + b), out value))
            {
                ListSms.Add(value);
            }

this will work for string like "2 2", which will make it "22" before .TryParse()

Community
  • 1
  • 1
huMpty duMpty
  • 14,346
  • 14
  • 60
  • 99
  • I guess that OP has spaces in the number like `"12 3"` and he want to parse it as `123`: _"problem looks like some space include in the text"_ – Tim Schmelter May 22 '14 at 10:07
  • One drawback of this solution is that if the `Sms_Nom` is not in a valid format the information will be lost. That is, to the list we will only add the `Sms_Nom`s that would be parsed by the `Parse` method anyway. We will not add `Sms_Nom`s that for instance contain a white space but are valid in any other respect. – PiotrWolkowski May 22 '14 at 10:08
  • @TimSchmelter: Oh didn't saw that part :) updated now – huMpty duMpty May 22 '14 at 10:13
0

use trim before int.Parse().

Also it's advisable to use int.tryParse() instead int.prase().

huMpty duMpty
  • 14,346
  • 14
  • 60
  • 99
DDave
  • 608
  • 6
  • 17
0

the problem looks like some space include in the text i brought in Sms_Nom, so this why I try to Parse it but it dosen't work !

So you have a sms.Sms_Nom string like "1 2 3" which should be parsed to 123?

If you have spaces in the text and you want to remove them, you can use this LINQ query which creates a new string from all non-space characters. Then use int.TryParse to check if it's an int:

var noSpaces = sms.Sms_Nom.Where(c => !Char.IsWhiteSpace(c));
string smsNom_noSpace = new String(noSpaces.ToArray());
int sms_Nom;
bool isInt = int.TryParse(smsNom_noSpace, out sms_Nom);
if(isInt)
    ListSms.Add(sms_Nom);
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939