0

I am getting the following error:

Object reference not set to an instance of an object

I don't know what is the cause of this error and how to solve it, here is my code:

while(dr.Read())
    {
     string variant = dr.GetString(0);
     int size = dr.GetInt32(1);
     int quantity = dr.GetInt32(2);

     DataRow x = dt.Rows
                  .Cast<DataRow>()
                  .Where(r => r["variant_name"].Equals(variant) && r["size"].Equals(size))
                  .FirstOrDefault();
                  x["quantity"] = quantity;             

      }

I'm getting the error on this line -> x["quantity"] = quantity; I'm wondering why it would give a null value because I checked in my database that it should return exactly one match.

Harvey
  • 399
  • 4
  • 15
  • 31

3 Answers3

3

FirstOrDefault returns null if the element is not found and you try to access this object.

Ken de Jong
  • 219
  • 1
  • 11
2

On the last line x is null, fix with

if(x != null)
   x["quantity"] = quantity;

This happens if your condition (.Where) doesn't yield a match.
At that point the FirstOrDefault return the Default part
and this is a null for a reference object as explained in MSDN

The default value for reference and nullable types is null.

Steve
  • 213,761
  • 22
  • 232
  • 286
  • I check my database and it should give at least one match. – Harvey May 27 '13 at 12:31
  • Sorry Sir...I don't know what to change in that line of code. What do you think is wrong in that line `.Where`? – Harvey May 27 '13 at 12:48
  • No, I was thinking about a reference problem, but this is not the case. Are you sure that the string in your database field "variant_name" is written in the exact case of your test condition (no spaces or linefeed also) – Steve May 27 '13 at 12:56
  • If I understand you correctly, Yes I'm pretty sure that it is the same. Actually I've tried to check what is the value of the `variant` by using a messagebox and it returns the same. – Harvey May 27 '13 at 13:05
  • I have no explanation then, if you have a row with the exact variant_name and exact size this code should return a match – Steve May 27 '13 at 13:13
0
while(dr.Read())
 {
  string variant = dr.GetString(0);
  int size = dr.GetInt32(1);
  int quantity = dr.GetInt32(2);

  DataRow x = dt.Rows
                .Cast<DataRow>()
                .Where(r => (r["variant_name"].ToString().Equals(variant) && Convert.ToInt32(r["size"]).Equals(size)))
                .FirstOrDefault();

   if (x != null)
   {
       x["quantity"] = quantity;  
   }       
 }

Thank you for your answer it helped me a lot. I just changed the line .Where a little bit and now it works for me. Thank you again!

Harvey
  • 399
  • 4
  • 15
  • 31