【问题标题】:Accessing SelectedItem from DDL within Repeater's ItemCommand在 Repeater 的 ItemCommand 中从 DDL 访问 SelectedItem
【发布时间】: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);

我正在尝试准备将数据推送到会话状态,因此我正在测试以确保它是可访问的。有什么我遗漏的东西,或者是访问该特定值的更好方法吗?

【问题讨论】:

  • 你在哪里绑定DropDownList1rptProducts的数据?
  • 这是在 ItemDataBound 中完成的

标签: c# asp.net repeater


【解决方案1】:

rptProducts_ItemCommand 事件中,您使用的是固定项目索引0,您需要选择触发项目命令的项目

下面这行代码将选择当前触发的项目。

DropDownList productDDL = (DropDownList)((RepeaterCommandEventArgs)e).Item.FindControl("DropDownList1");

【讨论】:

  • 缩小范围并让我远离 Null 异常,但 SelectedItem 始终是使用它的默认选项。我什至尝试将它放在 UpdatePanel 中以停止整页刷新
  • 在我的 Page_Load 中,我没有检查 (!Page.IsPostBack),因此您的更改随之解决了。非常感谢!干杯:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-08-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-09
  • 2011-04-03
  • 1970-01-01
相关资源
最近更新 更多