2014-09-04 42 views
2

我新的C#和.NET,我有一些代码抛出一个错误挣扎,它抛出的错误是:没有排在位置0查询

There is no row at position 0. 

这里是我的代码我得到了,据我可以看到,如果sql retours 0行404应该显示,但此刻我得到一个堆栈错误。

这是堆栈错误:

[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 

这里是我认为是引发错误的代码:

//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; 
} 
+2

你的DataTable'dt'不包含任何数据。 – 2014-09-04 10:39:30

+2

也许在位置0上实际上没有行? – 2014-09-04 10:39:50

+3

你可以使用'if(dt.Rows.Count> 0)'来检查它。但是你有没有加载'DataTable'?显示该代码。 – 2014-09-04 10:39:50

回答

0

检查是否有任何行:

if (
     dt.Rows.Count()>0 && 
     (
      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; 
} 
4

错误是零行没有数据 - 表dt为空。

代码期待那里是ATLEAST一行

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)) 
{ 
} 

您可以解决这个问题,通过增加监护条件,以检查是否有数据。

if (dt == null || 
    dt.Rows.Count < 1 || 
    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)) 
{ 
    // other code 
} 

或确定当您预期会有一些数据时可能没有数据的原因。

0

你应该使用要么

if(dt.Rows.Count > 0) 

if(dt == null)