11 Replies - 3189 Views - Last Post: 27 April 2011 - 09:13 AM Rate Topic: -----

#1 lando786  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 29
  • Joined: 27-April 11

NullReferenceException problem with foreach + DataRow

Posted 27 April 2011 - 08:30 AM

Hello
I get an annoying NullReferenceException whenever I use the following kind of code
foreach(DataRow row in datatable.Rows)
{
   str1 = row[0].ToString();
}


I usually work around this by adding a try catch like so:
foreach(DataRow row in datatable.Rows)
{

try
{
   str1 = row[0].ToString();
}
catch (NullReferenceException err)
{
   //do nothing
}



But I'm sure there must be something better as this does not look pleasant at all. Thanks in advance.

This post has been edited by lando786: 27 April 2011 - 08:30 AM


Is This A Good Question/Topic? 0
  • +

Replies To: NullReferenceException problem with foreach + DataRow

#2 here.to.code  Icon User is offline

  • D.I.C Head

Reputation: 20
  • View blog
  • Posts: 55
  • Joined: 15-February 11

Re: NullReferenceException problem with foreach + DataRow

Posted 27 April 2011 - 08:32 AM

View Postlando786, on 27 April 2011 - 08:30 AM, said:

Hello
I get an annoying NullReferenceException whenever I use the following kind of code
foreach(DataRow row in datatable.Rows)
{
   str1 = row[0].ToString();
}


I usually work around this by adding a try catch like so:
foreach(DataRow row in datatable.Rows)
{

try
{
   str1 = row[0].ToString();
}
catch (NullReferenceException err)
{
   //do nothing
}



But I'm sure there must be something better as this does not look pleasant at all. Thanks in advance.


Without the error point me at what is wrong the only thing I can think is maybe your Datatable has no DataRows when it gets to that loop. So if you did an if statement before the loop checking to make sure your datatable has at least 1 row that should solve the problem. If not please post the exact error you're getting :)
Was This Post Helpful? -1
  • +
  • -

#3 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5595
  • View blog
  • Posts: 11,970
  • Joined: 02-June 10

Re: NullReferenceException problem with foreach + DataRow

Posted 27 April 2011 - 08:41 AM

Check how many elements you have in your array before you just assume you have one.

row[0] assumes you have an element. Your null is saying you don't.

foreach(DataRow row in datatable.Rows)
{
   if (row.Length > 0) str1 = row[0].ToString();
}



Was This Post Helpful? 0
  • +
  • -

#4 lando786  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 29
  • Joined: 27-April 11

Re: NullReferenceException problem with foreach + DataRow

Posted 27 April 2011 - 08:42 AM

Oh sorry, The datatable has many rows, I import Excel Files sometimes over 4000 rows. I used the try catch assuming it's trying to read an extra row. Here is an actual snippet from my program

string getseries2 = "Select Comments, EUID FROM temp WHERE Series = 2 AND Comments is not null";
                DataTable series2 = new DataTable();
                SqlDataAdapter das = new SqlDataAdapter(getseries2,SQLCon);
                das.Fill(series2);

                foreach (DataRow row in series2.Rows)
                {
                    try
                    {
                        series2comments = row[0].ToString();
                        series2euid = row[1].ToString();
                        sqlcom.CommandText = "Select EU_Comments From temp Where Series = 1 AND EUID = '" + series2euid + "';";
                        series1comments = sqlcom.ExecuteScalar().ToString();
                        sqlcom.CommandText = "UPDATE temp SET EU_Comments = '" + series1comments + ";" + series2comments + "' WHERE EUID= '"+ series2euid + "';";
                        sqlcom.ExecuteScalar();
                    }
                    catch (NullReferenceException err)
                    {
                        
                    }
                }



Im not checking an array, the datatable has been pre-filled with either excel file import or sql query. If I remove the try catch I get the error I stated.

This post has been edited by lando786: 27 April 2011 - 08:43 AM

Was This Post Helpful? 0
  • +
  • -

#5 romil797  Icon User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 50
  • Joined: 24-April 11

Re: NullReferenceException problem with foreach + DataRow

Posted 27 April 2011 - 08:45 AM

The second one is not messy...again, try the loop if you don't like the second one. However, it is good practice to include a try, catch, finally statement
Was This Post Helpful? 1
  • +
  • -

#6 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5595
  • View blog
  • Posts: 11,970
  • Joined: 02-June 10

Re: NullReferenceException problem with foreach + DataRow

Posted 27 April 2011 - 08:46 AM

View Posthere.to.code, on 27 April 2011 - 09:32 AM, said:

the only thing I can think is maybe your Datatable has no DataRows when it gets to that loop.


Why that isn't the problem:
The OP's code is a Foreach loop. If there were no rows then the loop wouldn't execute at all, so the line causing the null reference would never be hit.

foreach(DataRow row in datatable.Rows)
{
   str1 = row[0].ToString();
}



Was This Post Helpful? 0
  • +
  • -

#7 lando786  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 29
  • Joined: 27-April 11

Re: NullReferenceException problem with foreach + DataRow

Posted 27 April 2011 - 08:48 AM

View Postromil797, on 27 April 2011 - 08:45 AM, said:

The second one is not messy...again, try the loop if you don't like the second one. However, it is good practice to include a try, catch, finally statement



Thanks romil, I guess if it is not considered messy and is the "correct" way to put it then this thread can be closed. I just assumed it was not good practice to include empty catch statements.
Was This Post Helpful? 0
  • +
  • -

#8 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5595
  • View blog
  • Posts: 11,970
  • Joined: 02-June 10

Re: NullReferenceException problem with foreach + DataRow

Posted 27 April 2011 - 08:52 AM

Quote

If I remove the try catch I get the error I stated.


You were already asked this, but you didn't answer.

One what line are you getting the null?
What object/variable is the null?
When your code stops with the error it stops on the line that caused it and you can check the variables/objects of that line to see their values. One of them is null.


Debugging tutorial
Debugging tips
Great debugging tips

You should at least try to avoid exceptions by checking your variables. It's just so darned easy to check them rather than cause an exception.
Try/catch are expensive and can slow down your program if used to excess.

Checking the values of your variables before you try to use them is just a good habit. Please review response #3 for an example of this.
Was This Post Helpful? 0
  • +
  • -

#9 lando786  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 29
  • Joined: 27-April 11

Re: NullReferenceException problem with foreach + DataRow

Posted 27 April 2011 - 08:59 AM

This is same example without try catch
foreach (DataRow row in series2.Rows)
                {

                    series2comments = row[0].ToString();
                    series2euid = row[1].ToString();
                    sqlcom.CommandText = "Select EU_Comments From temp Where Series = 1 AND EUID = '" + series2euid + "';";
                    series1comments = sqlcom.ExecuteScalar().ToString();
                    sqlcom.CommandText = "UPDATE temp SET EU_Comments = '" + series1comments + ";" + series2comments + "' WHERE EUID= '" + series2euid + "';";
                    sqlcom.ExecuteScalar();
                }



Error is on line
series1comments = sqlcom.ExecuteScalar().ToString();



Maybe I should not use Scalar?
Was This Post Helpful? 0
  • +
  • -

#10 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5595
  • View blog
  • Posts: 11,970
  • Joined: 02-June 10

Re: NullReferenceException problem with foreach + DataRow

Posted 27 April 2011 - 09:05 AM

Quote

Maybe I should not use Scalar?

Stop guess and start debugging.

While the execution is stopped on that line hover your mouse over each variable and you will see its value in the hothelp.

Hover over series1Comments and you will see its value.
Hover over sqlcom and you will see its value.

Which item on that line is null?

Or look in the Autos pallet and you will see all the variables and their values.

This post has been edited by tlhIn`toq: 27 April 2011 - 09:06 AM

Was This Post Helpful? 0
  • +
  • -

#11 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5595
  • View blog
  • Posts: 11,970
  • Joined: 02-June 10

Re: NullReferenceException problem with foreach + DataRow

Posted 27 April 2011 - 09:10 AM

You are also making a big assumption here:
series1comments = sqlcom.ExecuteScalar().ToString();



if the ExecuteScalar() method returns null it will break because then you are trying to do this:

series1comments = null.ToString();


Remember that assignments are evaluated from left to right then sent to the next method to the right.

You could confirm this by breaking down the compound line.

var temp = sqlcom.ExecuteScalar();
if (var != null) series1comments = temp.ToString();


I always recommend taking the longer approach as shown above until you are certain about your code. Then, after all is confirmed good, you can start to optimize if you like.
Was This Post Helpful? 1
  • +
  • -

#12 lando786  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 29
  • Joined: 27-April 11

Re: NullReferenceException problem with foreach + DataRow

Posted 27 April 2011 - 09:13 AM

[quote name='tlhIn`toq' date='27 April 2011 - 09:05 AM' timestamp='1303920333' post='1323859']

Quote

Hover over series1Comments and you will see its value.
Hover over sqlcom and you will see its value.

series1Comments = ""
sqlcom is a SQLCommand type and I'm not sure how one goes debugging that. It has several properties but only ones that are null are transaction and notification. CommandText is specified correctly and the connection is okay.

EDIT: thanks for that last post. It works great :D

This post has been edited by lando786: 27 April 2011 - 09:14 AM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1