【问题标题】:Dataset comparison with Null Value c#与空值 c# 的数据集比较
【发布时间】:2014-10-06 05:27:59
【问题描述】:

早安

我似乎无法在 Null 比较中使用我的数据集 我正在尝试发表声明(尝试如下),它只会在我的数据集为空时继续我的代码。

代码 1:

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

^ 只是跳过我的 if,我知道它是空的(检查了我的手表),即使它为 null 仍然继续。

代码 2:

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

^ 在我的 Tryparse 上崩溃。我知道你可以使用 Try catch,但我不想使用它,因为它会使我的程序运行速度变慢,而且它需要每天读取 10000 行......

错误:

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

意思是它什么都找不到,但我已经知道了。

编辑: 我不想出错。任何以前的方法,在其他情况下都有效,都会返回 indexoutofrange 错误。我会添加这个.. 数据集填充了来自 SQL 服务器的基于电话号码和其他数据的数据。 如果他找不到来自文本文件的电话号码,他将不返回任何内容,不返回行,不返回列,什么都没有。

提前致谢, DZ

【问题讨论】:

  • (string)dts.Tables[0].Rows[0]["RECID"] 的字符串值是什么,我猜它不为空,这就是为什么您的原始检查不起作用,也许是空字符串?那么检查((string)dts.Tables[0].Rows[0]["RECID"] != "") 是否可行?
  • 你可以试试if(!(dts.Tables[0].Rows[0]["RECID"] is DBNull))吗?
  • 对于第一行,您是否尝试与string.Empty 进行比较而不是null
  • 行 {System.Data.DataRowCollection} System.Data.DataRowCollection Count 0 int
  • 两次没有人..它仍然给我错误

标签: c# null dataset comparison


【解决方案1】:

你需要使用DBNull.Value而不是null

编辑:超出范围的索引可能意味着根本没有行。尝试用这个替换你的 if:

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

【讨论】:

  • 是的,但不要转换为字符串进行此比较。 `if (dts.Tables[0].Rows[0]["RECID"] != DBNull.Value)
  • 您是否将演员表移除为像 Olivier 提到的字符串?我在回答中忘记了这一点。
  • 我做了...在顶部添加了更多信息
【解决方案2】:

这一行:

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

需要

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

或者您可以删除该支票:

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

【讨论】:

    【解决方案3】:
    if((string)dts.Tables[0].Rows[0]["RECID"] is DBNull)
    { // will go here }
    

    【讨论】:

      【解决方案4】:

      找到了!

      int strTables = dts.Tables[0].Rows.Count; if (strTables == 1){ //代码放在这里}

      【讨论】:

        【解决方案5】:

        一种类型安全的替代方法是使用Field 扩展方法。对于空字段,它将返回“null”而不是 DBNull.Value。

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-03-15
          • 1970-01-01
          相关资源
          最近更新 更多