T.W.
T.W.

Reputation: 19

c# System.ArgumentNullException: Value cannot be null. Parameter name: source

The program that I have created needs to read information from a website and then store it. I am getting the error:

System.ArgumentNullException: Value cannot be null.
Parameter name: source
at System.Linq.Enumerable.Select[TSource,TResult](IEnumerable1 source, Func2 selector)

However it does not always run in error. As in sometimes it works and sometimes it doesn't work. How can this be? Here is the code that is giving me the error line 4.

IEnumerable<string> webtemp = Enumerable.Empty<string>();
if (datastring.Contains("today_nowcard-temp"))
{
    webtemp = doc.DocumentNode.SelectNodes("//div[@class = 'today_nowcard-temp']/span").Select(d => d.InnerText.Trim());

    foreach (var this_header in webtemp)
    {
        string[] temporary = this_header.Trim().Replace("Â", "-").Replace(" ", "-").Split('-');
        int f = (Convert.ToInt32(temporary[0]));
        _actualData[0].temp = GetCelsius(f);
        //Console.WriteLine(_actualData[0].temp);
    }
}

Upvotes: 0

Views: 4475

Answers (1)

ManishKumar
ManishKumar

Reputation: 1554

Reason behind this exception is the value that is returned by your SelectNodes method. Sometimes it returns null and then you try to perform Linq operation on null and it generate error. So you can perform a null check on this

var temp= doc.DocumentNode.SelectNodes("//div[@class = 'today_nowcard-temp']/span");

if(temp != null){
//TODO
}

Upvotes: 3

Related Questions