[英]Index out of range exception ASP C#
I'm building a products page for an e commence site. 我正在为e start网站建立产品页面。 I have two drop down lists. 我有两个下拉列表。
ddlProducts is connected to a SQL data source from which it retrieves the product information to populate it. ddlProducts连接到SQL数据源,SQL数据源从ddlProducts检索产品信息以进行填充。
ddlCategory contains a list of the product categories. ddlCategory包含产品类别的列表。
What I'm trying to do is to allow the user to select a product category from ddlCategory and then ddlProducts will populate with only the items from the database table that match that specific category. 我正在尝试做的是允许用户从ddlCategory中选择产品类别,然后ddlProducts将仅使用数据库表中与该特定类别匹配的项目进行填充。
ddlProducts then uses a method GetSelectedProduct() to retrieve the needed fields, for the product selected, from the database to display the information on the rest of the web page. ddlProducts然后使用方法GetSelectedProduct()从数据库中检索所选产品所需的字段,以在网页的其余部分上显示信息。
Here's the problem. 这是问题所在。 When I run the page, ddlProducts is populated with the products specific to the default selection from ddlCategory (in the case, the category is "Living Room"). 当我运行页面时,ddlProducts会填充特定于ddlCategory中默认选择的产品(在这种情况下,类别为“客厅”)。 Now as long as I do not try to change the selection in ddlCategory, then everything is fine. 现在,只要我不尝试在ddlCategory中更改选择,那么一切都很好。 I can use ddlProducts and everything does what it is supposed to do. 我可以使用ddlProducts,并且一切都会做它应该做的事情。
However if I try to change the selection on ddlCategory, then GetSelectedProduct() throws an Index out of range exception at line 但是,如果我尝试更改ddlCategory上的选择,则GetSelectedProduct()会在第1行抛出Index out of range异常
DataRowView row = productsTable[0]; DataRowView行= productsTable [0];
I can't figure out why. 我不知道为什么。
Can anybody offer any insight here?? 有人可以在这里提供任何见解吗? Thanks. 谢谢。
Drop Down List code 下拉列表代码
<asp:DropDownList ID="ddlCategory" runat="server" AutoPostBack="true">
<asp:ListItem Value="Living Room">Living Room</asp:ListItem>
<asp:ListItem Value="Dining Room">Dining Room</asp:ListItem>
<asp:ListItem Value="Bedroom">Bedroom</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="ddlProducts" runat="server"
AutoPostBack="True" DataSourceID="SqlDataSource1"
DataTextField="productName" DataValueField ="productID">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:OneStopConnectionString %>"
ProviderName="<%$ ConnectionStrings:OneStopConnectionString.ProviderName %>"
SelectCommand="SELECT [productID], [productName], [productRetail], [productImage] FROM [product] WHERE ([productRoom] = ?)">
<SelectParameters>
<asp:ControlParameter ControlID="ddlCategory" Name="productRoom" PropertyName="SelectedValue" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
Back code for the product page 产品页面的返回码
public partial class _Default : System.Web.UI.Page
{
private Product selectedProduct;
protected void Page_Load(object sender, EventArgs e)
{
//bind drop-down list on first load
//get and show product on every load
if (!IsPostBack) ddlProducts.DataBind();
selectedProduct = this.GetSelectedProduct();
lblName.Text = selectedProduct.Name;
lblUnitPrice.Text = selectedProduct.UnitPrice.ToString() + " each";
imgProduct.ImageUrl = "Images / Products /" + selectedProduct.ImageFile;
}
private Product GetSelectedProduct()
{
//get row from SqlDataSource based on value in dropdown list
DataView productsTable = (DataView)
SqlDataSource1.Select(DataSourceSelectArguments.Empty);
productsTable.RowFilter = string.Format("productID = '{0}'", ddlProducts.SelectedValue);
DataRowView row = productsTable[0]; <------line that is throwing the exception
//create a new product object and load with data from row
Product p = new Product();
p.ProductID = row["ProductID"].ToString();
p.Name = row["ProductName"].ToString();
p.UnitPrice = row["productRetail"].ToString();
p.ImageFile = row["productImage"].ToString();
return p;
}
You need to databind ddlProducts before calling GetSelectedProduct, otherwise it isn't initialized correctly and you can't reference the SelectedValue. 您需要在调用GetSelectedProduct之前对ddlProducts进行数据绑定,否则它将没有正确初始化,因此您将无法引用SelectedValue。
Since ddlProducts.SelectedValue is returning an unexpected value, your RowFilter doesn't find any rows, so when you go and reference the first row, it then throws an error. 由于ddlProducts.SelectedValue返回一个意外值,因此您的RowFilter找不到任何行,因此当您引用第一行时,它将引发错误。
Referencing the selectedValues of DropdownLists can be very tricky because they are usually initialized very late in the lifecycle of the request. 引用DropdownLists的selectedValues可能非常棘手,因为它们通常在请求的生命周期中很晚才初始化。 Even setting the selectedValue often times can't be read back out during the same request because on set it stored the value in a temporary location for later use during the actual databinding. 即使设置selectedValue通常也无法在同一请求期间被读出,因为在设置时,它将值存储在一个临时位置中,供以后在实际数据绑定期间使用。 Unless forced, the databinding doesn't happen until right before render, which is way after Load_Page happens. 除非强制执行,否则数据绑定只有在渲染之前(即Load_Page发生之后)才会发生。 Hope that clarifies the why. 希望能阐明原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.