【问题标题】:Exception raised if the table has no rows如果表没有行,则会引发异常
【发布时间】:2013-01-08 15:47:57
【问题描述】:

在下面的 if 语句中,我需要检查第一个表中的第一行/列是否包含字符串,但如果表没有行,则会出现异常。

例外是:

"System.IndexOutOfRangeException = {"位置 0 处没有行。"}"

代码sn-p:

'if the table has no rows then an exception happens here
If myDataSet.Tables(0).Rows(0)(0).ToString <> "MyMessage" then


'do this - redirect

Else

 myDataSet.Tables(0).Rows(0)(0) = "no message"

End If

你能帮忙吗?

【问题讨论】:

  • 异常信息是什么?
  • 嗨,我更新了帖子 - 谢谢

标签: c# .net vb.net


【解决方案1】:

它会引发异常,因为您假设存在一行,并带有以下语句 If myDataSet.Tables(0).Rows(0)(0)

你应该先通过If myDataSet.Tables(0).Rows.Count &gt; 0检查你是否有一行

【讨论】:

    【解决方案2】:

    if..else 块包装在if 中:

    if myDataSet.Tables(0).Rows.Count > 0 then 
    //your code here
    end if
    

    【讨论】:

      【解决方案3】:

      如果结果集中没有行,您将无法访问 myDataSet.Tables(0).Rows(0)。先检查行数:

      If myDataSet.Tables.Count <> 0 AND myDataSet.Tables(0).Rows.Count <> 0 Then
          ' your code
      End If
      

      【讨论】:

        【解决方案4】:

        您应该首先检查您的表格是否有任何行

        If myDataSet.Tables(0).Rows.Count <> 0 then
        
        'do stuff
        

        【讨论】:

          猜你喜欢
          • 2011-10-18
          • 1970-01-01
          • 2013-07-29
          • 1970-01-01
          • 2017-01-12
          • 1970-01-01
          • 2019-04-25
          • 2014-02-10
          • 1970-01-01
          相关资源
          最近更新 更多