猿问

从Repeater的ItemCommand中的DDL访问SelectedItem

大家好-我正在尝试从位于Repeater内的DropDown列表中访问SelectedItem值,但是我收到抛出的Null异常。该转发器将迭代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);

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


料青山看我应如是
浏览 149回答 1
1回答

桃花长相依

在rptProducts_ItemCommand事件中,你使用的是固定的项目索引0,您需要选择解雇项命令项目代码下面的行将选择当前触发的项目。DropDownList&nbsp;productDDL&nbsp;=&nbsp;(DropDownList)((RepeaterCommandEventArgs)e).Item.FindControl("DropDownList1");
随时随地看视频慕课网APP
我要回答