简体   繁体   中英

Dataset comparison with Null Value c#

Goodday

I can't seem to use my dataset in a Null comparison I'm trying to make an statement (attempts go below) where it will only continue my code when my dataset is empty.

Code 1:

if ((string)dts.Tables[0].Rows[0]["RECID"] != null)

^ just skips my if, I know that it's empty (checked my watch), still continues even when it is null.

Code 2:

 long Recid = 0;
 Boolean checkrecid = long.TryParse((string)dts.Tables[0].Rows[0]["RECID"], out Recid);
 if (checkrecid == false)

^ Crashes at my Tryparse. I know you can use Trycatching, but I don't want to use it, cause it will make my program run slower, and it needs to read a good 10000 lines a day ...

Error:

A first chance exception of type 'System.IndexOutOfRangeException' occurred in System.Data.dll

Meaning that it can't find anything, but I know that already.

EDIT: I do not want an error. Any previous methods, who all work in other cases, return an indexoutofrange error. I'll add this .. The dataset is filled with data from an SQL server based on phonenumbers and other data. If he can't find the phonenumber, which comes from a text file, he will return nothing, no row, no column, nothing.

Thanks in advance, DZ

You need to use DBNull.Value instead of null

EDIT: Index outside the bounds may mean there are no rows at all. Try replacing your if with this:

if (dts.Tables[0].Rows.Count > 0 && dts.Tables[0].Rows[0]["RECID"] != DBNull.Value)
{
}

This line:

if ((string)dts.Tables[0].Rows[0]["RECID"] != null)

needs to be

if ((string)dts.Tables[0].Rows[0]["RECID"] != DBNull.Value)

Or you could delete that check:

Boolean checkrecid = long.TryParse((dts.Tables[0].Rows[0]["RECID"] ?? string.Empty), out Recid);

A type-safe alternative is using Field extension method. It will return 'null' instead of DBNull.Value for empty fields.

if (dts.Tables[0].Rows[0].Field<string>("RECID") != null)
if((string)dts.Tables[0].Rows[0]["RECID"] is DBNull)
{ // will go here }

Found it!

int strTables = dts.Tables[0].Rows.Count; if (strTables == 1){ //code goes here}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM