所以在这个数据集中我想检查男孩的数量和女孩的数量以及总数。数据集返回Table[1]
,其中包含两行,女孩数和男孩数。row[0][1]
返回女孩数,row[1][1]
返回男性数
但只要Table1
返回男孩或女孩的单行.ie计数,IndexOutOfRangeException
就会在第一个There is no row at position 1
处抛出if
。
我检查空数据流的方式是否正确?
以下是代码段
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
}
答案 0 :(得分:0)
如果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()
请记住,count和index在编码方面有所不同。
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
{
}
}