2 Replies - 410 Views - Last Post: 18 August 2010 - 07:24 AM Rate Topic: -----

#1 salomon.frid  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 03-August 10

testing for null in ado tables

Posted 17 August 2010 - 09:21 PM

While trying to read the records in a table that belongs to a dataset, I test to verify if the record does not exist:
int i;
while (dataset.table["mytable"].rows[i] != null)
       {
          // do some work
          i++;
       }


once i reaches the value where there is no corresponding record, c# will issue an exception
I worked around it with the following code:
foreach (DataRow row in ds.Tables[0].Rows)
// do work


but i am not sure why the first code does not work
thnx

This post has been edited by AdamSpeight2008: 17 August 2010 - 09:30 PM
Reason for edit:: Fixing Code tags :code:


Is This A Good Question/Topic? 0
  • +

Replies To: testing for null in ado tables

#2 n8wxs  Icon User is offline

  • --... ...-- -.. . -. ---.. .-- -..- ...
  • member icon

Reputation: 972
  • View blog
  • Posts: 3,878
  • Joined: 07-January 08

Re: testing for null in ado tables

Posted 17 August 2010 - 10:09 PM

You get the exception because you trying to access an element outside the array.

You could use a try()...catch() block to catch the exception but your workaround is probably simpler.
Was This Post Helpful? 0
  • +
  • -

#3 Curtis Rutland  Icon User is online

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 4453
  • View blog
  • Posts: 7,755
  • Joined: 08-June 10

Re: testing for null in ado tables

Posted 18 August 2010 - 07:24 AM

Yes, values outside the bounds of an array won't be null, they'll throw an IndexOutOfBoundsException.

Think of it this way. Your "while" loop will keep going until "i" becomes larger than the array. Then when you try to access that index of the array, the array says "no, that doesn't exist" and throws an error.

You could do this with a "for" loop":
for(int i=0; i<dataset.table["mytable"].rows.Count; i++)
  //do work


But the foreach is a more elegant solution if you're not changing the collection.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1