-1

Ok so when I run this i run into a null exception in the if statement on workshops[2]. The messagebox shows the value that i expected. Thoughts?

foreach (string[] workshops in data.aWorkJag)
{
    MessageBox.Show(workshops[2].ToString());
    if (workshops[1].ToString() == wkshpConfCode)
    {
        toAddList.Add(workshops[2].ToString());
    }
}

The exception is being thrown on the line

toAddList.Add(workshops[2].ToString());

John Saunders
  • 157,405
  • 24
  • 229
  • 388
SoulOfSet
  • 181
  • 7
  • 1
    You are displaying third item [2], but accessing second item [1], which I think is null – Sergey Berezovskiy Feb 28 '14 at 01:35
  • toAddList.Add(workshops[2].ToString()); is what throws the null exception sorry. – SoulOfSet Feb 28 '14 at 01:36
  • 1
    Welcome to Stack Overflow! Almost all cases of `NullReferenceException` are the same. Please see "[What is a NullReferenceException in .NET?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net)" for some hints. – John Saunders Feb 28 '14 at 01:54

2 Answers2

1

Looks like workshops[2] has a value but workshops[1] is null. The ToString() method throws an exception if you call it on a null value.

Assuming that's not just a typo, you can use Convert.ToString(), which does a null check and returns an empty string:

if (Convert.ToString(workshops[1]) == wkshpConfCode)
Grant Winney
  • 61,140
  • 9
  • 100
  • 152
1

Check to make sure that toAddList is initialized

TYY
  • 2,622
  • 1
  • 11
  • 14
  • Did something silly and had the variable set to null. Would seem rather obvious but I do that allot. Thank you. – SoulOfSet Feb 28 '14 at 01:42