Search code examples
c#asp.netddl

Dynamic DropdownList


I have 2 questions: First, I put a DDL in a repeater in my .aspx. Here's my code:

<HeaderTemplate>
    <ul class ="horizontal">
  </HeaderTemplate>
  <ItemTemplate>
    <li>
<img src="<%# DataBinder.Eval(Container.DataItem, "ImagePath") %>" width="60" height="40" alt = "<%# DataBinder.Eval(Container.DataItem, "ProductName") %>"/>
        <p>ID: <asp:Literal ID="ProductIDLiteral" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "ProductID") %>'></asp:Literal></p>
        <p>
            <asp:Literal ID="NameLiteral" runat="server" Text="Name: "></asp:Literal><asp:Literal ID="ProductNameLiteral" runat="server" Text = '<%# DataBinder.Eval(Container.DataItem, "ProductName") %>'></asp:Literal>
        </p>
        <p>
            <asp:Literal ID="Literal1" runat="server" Text="Price: "></asp:Literal><asp:Literal ID="UnitPriceLiteral" runat="server" Text = '<%# DataBinder.Eval(Container.DataItem, "UnitPrice") %>'></asp:Literal>
         </p>
         <p> <asp:Literal ID="QuantityLiteralLiteral" runat="server" Text="Quantity: "></asp:Literal><asp:DropDownList ID="DDLQuantity" runat="server" ><asp:ListItem></asp:ListItem>
        </asp:DropDownList></p>
        <asp:Literal ID="Literal" runat="server"></asp:Literal>
 </li>
  </ItemTemplate>
  <FooterTemplate>
      <asp:Button ID="Button1" runat="server" Text="Validate!" />
    </ul>
  </FooterTemplate>
</asp:Repeater>

well, the first question, is How can I populate my DDL from the code behind? Then How can I do, to populate the DDL with <1-2-3-4> If the source value is 4. Thank you!!


Solution

  • You can use the Init event to populate a DropDownList:

    protected void DropDownList1_Init(object sender, EventArgs e)
    {
        for (int i = 1; i <= 4; i++)
        {
            ((DropDownList)sender).Items.Add(i.ToString());
        }
    }