我一直在接收错误消息“索引0是负数或行数以上”,它将SQL中的特定行声明为主题行。我已经尝试过查看其他示例,但我无法解决如何解决这个特定问题。从我的POV开始,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;
}
服务器错误:
说明:执行期间发生未处理的异常 当前的网络请求。请查看堆栈跟踪了解更多信息 有关错误的信息以及它在代码中的起源。
异常详细信息: 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
答案 0 :(得分:1)
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;
}
}