This question already has an answer here:
“Index 0 is either negative or above row count” error C#
                                
                                    (1个答案)
                                
                        
                                2年前关闭。
            
                    
我不断收到错误消息“索引0为负数或高于行数”,该行从SQL声明特定行作为主题行。我尝试查看其他示例,但无法解决该特定问题。从我的观点来看,SQL并不是问题,因为否则一切都可以正确读取。

码:

private Product GetSelectedProduct()
{
    DataView productsTable = (DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty);
    productsTable.RowFilter = string.Format("ProductID = '{0}'", ddlProducts.SelectedValue);
    DataRowView row = (DataRowView)productsTable[0];

    Product p = new Product();
    p.ProductID = row["ProductID"].ToString();
    p.Name = row["Name"].ToString();
    p.ShortDescription = row["ShortDescription"].ToString();
    p.LongDescription = row["LongDescription"].ToString();
    p.UnitPrice = (decimal)row["UnitPrice"];
    p.ImageFile = row["ImageFile"].ToString();
    return p;
}


服务器错误:


  说明:在执行期间发生未处理的异常
  当前的Web请求。请查看堆栈跟踪以获取更多信息
  有关错误及其在代码中起源的信息。
  
  异常详细信息:System.IndexOutOfRangeException:索引0为
  负数或以上的行数。


堆栈跟踪:

[IndexOutOfRangeException: Index 0 is either negative or above rows count.]
   System.Data.DataView.GetRow(Int32 index) +1788553
   System.Data.DataView.get_Item(Int32 recordIndex) +13
   Order.GetSelectedProduct() in f:\Year 2\Internet Applications Programming\Assignment 2\Lab 3 - 06-03-17\Ex04Cart\Order.aspx.cs:23
   Order.Page_Load(Object sender, EventArgs e) in f:\Year 2\Internet Applications Programming\Assignment 2\Lab 3 - 06-03-17\Ex04Cart\Order.aspx.cs:12
   System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +51
   System.Web.UI.Control.OnLoad(EventArgs e) +95
   System.Web.UI.Control.LoadRecursive() +59
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2952

最佳答案

productsTable不包含任何内容。因此productsTable[0]超出范围。

因此,让我们在过滤后检查是否有任何记录。

private Product GetSelectedProduct()
{
    DataView productsTable = (DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty);
    productsTable.RowFilter = string.Format("ProductID = '{0}'", ddlProducts.SelectedValue);

    if (productsTable.Count > 0)
    {
        DataRowView row = (DataRowView)productsTable[0];

        Product p = new Product();
        p.ProductID = row["ProductID"].ToString();
        p.Name = row["Name"].ToString();
        p.ShortDescription = row["ShortDescription"].ToString();
        p.LongDescription = row["LongDescription"].ToString();
        p.UnitPrice = (decimal)row["UnitPrice"];
        p.ImageFile = row["ImageFile"].ToString();
        return p;
    }
    else
    {
        // Or throw an exception, if your logic dictates that this method SHOULD return a record.
        return null;
    }
}

10-08 08:41