Search code examples
c#asp.netrepeater

Accessing SelectedItem from DDL within Repeater's ItemCommand


Hey all — I'm trying to access the SelectedItem value from a DropDown list that is housed within a Repeater, but I am receiving a Null Exception that is thrown. This repeater would iterate over upwards of 10 "products". Here is the code from my Web Form:

 <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>

And the code from the .cs file where I'm trying to access DropDownList1's SelectedItem value.

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);
    }

}

The Exception is being thrown at this line:

int Qty = Convert.ToInt32(productDDL.SelectedItem.Text);

I'm trying to prep that data to be pushed into a Session state, so I'm testing to ensure it is accessible. Is there something I'm missing and or a better way to access that specific value?


Solution

  • In rptProducts_ItemCommand event you are using fixed item index 0, you need to select the item that fired item command

    Below line of code will select the current triggered item.

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