I'm developing software that grabs data from an html table. So this line:
team.SelectSingleNode(".//td[@class='number total won total_won']")?.InnerText.Trim();
returns: ""
(I'm using html agility pack for DOM manipulation.)
And the complete line is this:
Convert.ToInt32(
team.SelectSingleNode(
".//td[@class='number total won total_won']")
?.InnerText.Trim());
This returns an exception (incorrect format exception).
Any idea to solve this?
You can use int.TryParse
instead of Convert.ToInt32
int myInt;
if(!int.TryParse(team.SelectSingleNode(".//td[@class='number total won total_won']")?.InnerText.Trim(), out myInt))
{
myInt = 0;
}
I know, but I've 30+ lines of code, so I should add a lot of if conditions... – Ilnumerouno just now
You can write a helper method instead.
public static class Converter{
public static int ConvertToInt(string stringAsInt){
int myInt;
return int.TryParse(stringAsInt, out myInt) ? myInt : 0;
}
}
Calling code.
var parsedInt = Converter.ConvertToInt(team.SelectSingleNode(".//td[@class='number total won total_won']")?.InnerText.Trim());