Reputation: 542
I'm trying to populate a Data Table with a range of years to be used in a Data List. My application has five lists on the page and I have buttons to scroll through the years: 1995, 1996, 1997 and so on.
However, if year 1997 does not exist in the database I get an error in my application: There is no row at position 2
. How can I prevent this? if (dt.Rows.Count > 0)
checks that data exists but how do I check that data exists before setting the value of the other strings (SecondYear, ThirdYear, FourthYear, FifthYear)
if (dt.Rows.Count > 0)
{
if (!string.IsNullOrEmpty(dt.Rows[0][0].ToString()))
{
FirstYear = dt.Rows[0][0].ToString();
}
if (!string.IsNullOrEmpty(dt.Rows[1][0].ToString()))
{
SecondYear = dt.Rows[1][0].ToString();
}
if (!string.IsNullOrEmpty(dt.Rows[2][0].ToString()))
{
ThirdYear = dt.Rows[2][0].ToString();
}
if (!string.IsNullOrEmpty(dt.Rows[3][0].ToString()))
{
FourthYear = dt.Rows[3][0].ToString();
}
if (!string.IsNullOrEmpty(dt.Rows[4][0].ToString()))
{
FifthYear = dt.Rows[4][0].ToString();
}
}
This does not work:
if (dt.Rows[1][0].Count > 0)
{
SecondYear = dt.Rows[1][0].ToString();
}
Upvotes: 0
Views: 379
Reputation: 1985
Instead of indexers, please try to use DataRowExtensions (or DataSetExtensions) as below
var o1 = dt.Rows[1].Field<string>(0);
or more readable using column name:
var o2 = dt.Rows[1].Field<string>("columnName");
Upvotes: 1
Reputation: 46909
Check that the nr. of rows are larger than or equal to the year row you are checking.
if(dt.Rows.Count >= 1)
SecondYear = dt.Rows[1][0].ToString();
Upvotes: 0