Link to home
Start Free TrialLog in
Avatar of 3DGames
3DGames

asked on

Loop Problem (Object Reference Problem)

Hi.
My problem is simple, that's why i think the soulution won't be...

I Have this loop:

for( int y=0; y<oDS.Tables["Databases"].Rows.Count; y++ )
{
      oLI = new ListItem( oDS.Tables["Databases"].Rows[y]["TableCatalog"].ToString(), oDS.Tables["Databases"].Rows[y]["TableCatalog"].ToString() );
      dropDatabase.Items.Add( oLI );
}

It gave me a object reference error. But the quick watch shows "oDS.Tables["Databases"].Rows[y]["TableCatalog"]" with the prober value when I run the DEBUG.

Then I solved it with this:

string strTemp;

for( int y=0; y<oDS.Tables["Databases"].Rows.Count; y++ )
{
      strTemp = oDS.Tables["Databases"].Rows[y]["TableCatalog"].ToString();
      oLI = new ListItem( strTemp , strTemp );
      dropDatabase.Items.Add( oLI );
}

Why the hell the first one didn't worked out?

Thanks!
Roberto Colnaghi Junior
Avatar of testn
testn

Is tablecatalog field ntext or binary?
Avatar of 3DGames

ASKER

It is a VARCHAR(64) SQL SERVER 2000 datatype.
ASKER CERTIFIED SOLUTION
Avatar of TheAvenger
TheAvenger
Flag of Switzerland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
it would actually be BETTER (more efficient) to use somethig like this:

Sting  strRow as String;
foreach (DataRow row in oDS.Tables["Databases"].Rows)
{
     strRow = row["TableCatalog"].ToString();
     oLI = new ListItem(strRow,strRow);
     dropDatabase.Items.Add( oLI );
}

this makes a SINGLE call to the row["TableCatalog"].ToString() method, and 'caches' the result as strRow, which can then be used twice, rather than requiring the toString method to be executed twice.  This will be more efficient, performance wise.

AW

Arthur_Wood: 3DGames already made this but he had a problem when the calls to ToString were two (have a look at the above posts) so I suggested that he calls the ToString method again twice to see if there is any difference
Avatar of 3DGames

ASKER

Well... Thanks for the solution!

But the question remains.... why my first loop didn't worked?

Your answer(TheAvenger) are almost the same as it...... Ok, it is much more clean and easier to read :) , but I think that both should work.