【发布时间】:2015-10-09 19:01:33
【问题描述】:
我正在为 e 开始网站构建产品页面。我有两个下拉列表。
ddlProducts 连接到 SQL 数据源,从中检索产品信息以填充它。
ddlCategory 包含产品类别列表。
我想要做的是允许用户从 ddlCategory 中选择一个产品类别,然后 ddlProducts 将只填充数据库表中与该特定类别匹配的项目。
ddlProducts 然后使用 GetSelectedProduct() 方法从数据库中检索所选产品所需的字段,以在网页的其余部分显示信息。
这就是问题所在。当我运行该页面时,ddlProducts 填充了特定于 ddlCategory 的默认选择的产品(在这种情况下,类别是“客厅”)。现在只要我不尝试更改 ddlCategory 中的选择,那么一切都很好。我可以使用 ddlProducts 并且一切都在做它应该做的事情。
但是,如果我尝试更改 ddlCategory 上的选择,则 GetSelectedProduct() 会在行抛出 Index out of range 异常
DataRowView 行 = productsTable[0];
我不知道为什么。
有人可以在这里提供任何见解吗? 谢谢。
下拉列表代码
<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>
产品页面返回码
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;
}
【问题讨论】:
-
您是否检查过以确保行过滤器实际上正在返回数据? productID 是整数还是字符串?您的过滤器使它看起来像一个字符串,但如果不是,那可能是问题的一部分。
-
什么是
Product它是DataSet、DataTable、..Class..显示所有相关代码还有为什么不将您的DataView 绑定到DataTableDataTables 也支持.Select 过滤功能