I am new to C# and .NET and I am struggling with some code that is throwing a error, the error it throws is:
There is no row at position 0.
Here is my code that I got, as far as I can see if the sql returs 0 rows the 404 should be displayed, however at the moment I am getting a stack error.
This is the stack error:
[IndexOutOfRangeException: There is no row at position 0.]
System.Data.RBTree`1.GetNodeByIndex(Int32 userIndex) +2409382
System.Data.DataRowCollection.get_Item(Int32 index) +20
Targetting.ArticlePage.Page_Load(Object sender, EventArgs e) in C:\SRC\Site1\Web\Article\Trunk\Article.aspx.cs:78
CommonBasePageClass.BaseWebPage.OnLoad(EventArgs e) +50
System.Web.UI.Control.LoadRecursive() +71
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3178
Here is the code that I believe is throwing the error:
//If the article is Archived or Unknown or has expired then all users should be shown an "unavailable" message instead of the content
if (dt.Rows[0]["pagestatusid"].ToString() == "3" || dt.Rows[0]["pagestatusid"].ToString() == "0" || (dt.Rows[0]["expirydate"] != DBNull.Value && DateTime.Parse(dt.Rows[0]["expirydate"].ToString()) < DateTime.Now))
{
pnlDraftWarning.Visible = false;
pnlContentNotAvailable.Visible = true;
pnlMainContent.Visible = false;
Response.StatusCode = 404;
return;
}
Best Solution
The error is that there is no data at row zero - the table
dt
is empty.The code is expecting there to be atleast one row
You can work around this issue by adding a guard condition to check if there is data.
or identify the reason why there might not be data when you are expecting there to be some.