【问题标题】:How to check if an individual datatable row is empty or not?如何检查单个数据表行是否为空?
【发布时间】:2015-03-28 06:38:08
【问题描述】:

所以在这个数据集中,我想检查男孩的数量和女孩的数量以及总数。数据集返回Table[1],其中有两行,女孩数量和男孩数量。row[0][1] 返回女孩数量,row[1][1] 返回男性数量

但每当Table1 返回单行,即男孩或女孩的计数时,IndexOutOfRangeException 就会在第一个if 本身抛出There is no row at position 1

我检查空数据行的方法是否正确?

这里是代码sn-p

 if (dsStudent != null && dsStudent.Tables.Count > 0 && dsStudent.Tables[0].Rows.Count > 0)
        {
            if (!(dsStudent.Tables[1].Rows[0]==null) && !(dsStudent.Tables[1].Rows[1]==null)) //both are present
            {
                lblbNumOfGirls.Text = dsStudent.Tables[1].Rows[0][1].ToString().Trim();
                lblNumOfBoys.Text = dsStudent.Tables[1].Rows[1][1].ToString().Trim();
            }
            else if ((dsStudent.Tables[1].Rows[0][1].Equals(string.Empty))) //if girls are 0
            {
                lblbNumOfGirls.Text="0";
                lblNumOfBoys.Text = dsStudent.Tables[1].Rows[1][1].ToString().Trim();
            }

            else //if boys are 0
            {
                 lblNumOfBoys.Text="0";
                 lblbNumOfGirls.Text = dsStudent.Tables[1].Rows[0][1].ToString().Trim();
            }

            lblNumStudents.Text = (int.Parse(lblNumOfBoys.Text) + int.Parse(lblbNumOfGirls.Text)).ToString(); //total number of students
         }

【问题讨论】:

    标签: c# winforms exception dataset datarow


    【解决方案1】:

    如果Table1 仅返回 1 行,则该 1 行的索引为“0”。这就是为什么你会收到Index out of bound 问题。

    如果您只在有两行或更多行(男性一行,女性一行,其他行)时运行代码,您的检查应为dsStudent.Tables[0].Rows.Count > 1

    因为你的检查是dsStudent.Tables[0].Rows.Count > 0,所以你的代码在只有1行时会进入if语句,但是当你试图访问第二行时会抛出异常dsStudent.Tables[1].Rows[1][1].ToString().Trim()

    记住,计数和索引在编码上是不同的。

    Row 1: index = 0
    Row 2: index = 1
    Row 3: index = 2
    ...
    

    -- 编辑--

    好的,我明白了。所以问题是你正在阅读Table1,但没有先验证它。

    这是抛出异常的那一行:

    if (!(dsStudent.Tables[1].Rows[0]==null) && !(dsStudent.Tables[1].Rows[1]==null))
    

    您正在阅读Rows[0]Rows[1],但该行可能不存在。

    例如,如果您的表仅包含 1 行,则条件 dsStudent.Tables[1].Rows[1] 的第二部分将抛出异常,因为 Rows[1] 不存在。

    要检查您的表是否至少包含两行,最简单的方法是这样做:

    if (dsStudent.Tables[1].Rows.Count >= 2)
    {
    }
    

    我的建议是检查 if 语句中的男孩和女孩。

    另外,如果值为null,则不能与String.Empty比较

    NULL 不等于String.Empty

    if (dsStudent.Tables[1].Rows.Count >= 2)
    {
        if (DBNull.Value.Equals(dsStudent.Tables[1].Rows[0][1])) //girls = 0
        {
        }
        if (DBNull.Value.Equals(dsStudent.Tables[1].Rows[1][1])) //boys = 0
        {
        }
    }
    

    【讨论】:

    • 当女孩和男孩都在场时,我得到两排。只有当其中一个在场时,我才得到单排
    • @saurabh64 请查看我的更新答案,我猜您对计数和索引感到困惑。
    • Table[0] 是一个单独的表,Table[1] 是单独的。与 Table[0] 相关的一切都工作正常
    猜你喜欢
    • 2016-07-15
    • 2012-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多