在将 SQL 中的特定行声明为主题行的行上,我不断收到“索引 0 为负数或高于行数”的错误消息。我尝试过查看其他示例,但我无法弄清楚如何解决这个特定问题。从我的角度来看,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;
}
服务器错误:
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.IndexOutOfRangeException: Index 0 is either negative or above rows count.
堆栈跟踪:
[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;
}
}
关于c# - 索引 0 为负数或高于行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42628220/