【发布时间】:2018-04-22 19:13:07
【问题描述】:
大家好——我正在尝试从位于中继器内的下拉列表中访问 SelectedItem 值,但我收到了抛出的空异常。该转发器将迭代超过 10 个“产品”。这是我的 Web 表单中的代码:
<asp:repeater ID="rptProducts" runat="server" OnItemDataBound="rptProducts_ItemDataBound" OnItemCommand="rptProducts_ItemCommand">
<ItemTemplate>
<div class="col-md-8 col-md-offset-2 product">
<img src="<%# Eval("ImageFile") %>" class="col-xs-12" alt="<%# Eval("Name") %> Product Image"/>
<h3><%# Eval("Name") %></h3>
<p><%# Eval("ShortDescription") %></p>
<asp:DropDownList ID="DropDownList1" runat="server"></asp:DropDownList>
<asp:Button ID="Button1" runat="server" Text="Add to Cart" CommandName="click" CommandArgument='<%# Eval("Name") %>' UseSubmitBehavior="false" />
</div>
</ItemTemplate>
</asp:repeater>
还有我试图访问 DropDownList1 的 SelectedItem 值的 .cs 文件中的代码。
protected void rptProducts_ItemCommand(object sender, CommandEventArgs e)
{
Repeater rpt = (Repeater)sender;
DropDownList productDDL = (DropDownList)rpt.Items[0].FindControl("DropDownList1");
int Qty = Convert.ToInt32(productDDL.SelectedItem.Text);
Debug.WriteLine(rpt.ID);
if (e.CommandName == "click")
{
Debug.WriteLine("Clicked " + e.CommandArgument.ToString() + "; Quantity: " + Qty);
}
}
在这一行抛出异常:
int Qty = Convert.ToInt32(productDDL.SelectedItem.Text);
我正在尝试准备将数据推送到会话状态,因此我正在测试以确保它是可访问的。有什么我遗漏的东西,或者是访问该特定值的更好方法吗?
【问题讨论】:
-
你在哪里绑定
DropDownList1和rptProducts的数据? -
这是在 ItemDataBound 中完成的