简体   繁体   English

数据集与空值C#的比较

[英]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. 我似乎无法在Null比较中使用我的数据集,我试图做出一个声明(尝试如下),该语句仅在我的数据集为空时才继续执行我的代码。

Code 1: 代码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: 代码2:

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

^ Crashes at my Tryparse. ^我的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 ... 我知道您可以使用Trycatching,但是我不想使用它,因为它会使我的程序运行缓慢,并且每天需要读取10000行。

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. 所有在其他情况下都可以使用的先前方法,都将返回indexoutofrange错误。 I'll add this .. The dataset is filled with data from an SQL server based on phonenumbers and other data. 我将添加此..数据集填充有基于电话号码和其他数据的SQL Server数据。 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 在此先感谢DZ

You need to use DBNull.Value instead of null 您需要使用DBNull.Value而不是null

EDIT: Index outside the bounds may mean there are no rows at all. 编辑:超出范围的索引可能意味着根本没有行。 Try replacing your if with this: 尝试用以下方法替换if:

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. 对于空字段,它将返回“ null”而不是DBNull.Value。

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; int strTables = dts.Tables [0] .Rows.Count; if (strTables == 1){ //code goes here} if(strTables == 1){//代码在这里}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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