How can I create an asp:button iteratively in code behind aspx file?

106 Views Asked by At

So essentially I am making a "cart" for a website I am doing as an extra side project. In each item in cart, I am attempting to put a button to remove the item from the cart. The issue is, it is not possible to create an asp:button from the code behind. Everything I have read says to make a placeholder or panel and then put a button inside that, but since I wont know how many items the user has in their cart, I cant just put X amount of placeholders in my aspx file.

My aspx code (so far):

<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">

    <div id="emptyCart" style="text-align: center;" runat="server">
        <h1>Your cart is empty!</h1>
    </div>

    <div id="cart" runat="server">



    </div>

</asp:Content>

My background writing for making the items appear in cart (this would be for just 1 item):

                    if (cart.InnerHtml == "")
                    {
                        cart.InnerHtml = "<div class='jumbotron'>";
                    }
                    else
                    {
                        cart.InnerHtml += "<div class='jumbotron'>";
                    }
                    cart.InnerHtml += "<div style='display:block;'>";
                    cart.InnerHtml += "<h3 style='display:inline-block'>Featured</h3>";
                    cart.InnerHtml +=  "<h4 style = 'display:inline-block; float:right;' > Special title treatment</h4>";
                    cart.InnerHtml += "</div>";
                    cart.InnerHtml += "<div>";
                    cart.InnerHtml += "<h6>With supporting text below as a natural lead-in to additional content.</h6>";
                    cart.InnerHtml += "<asp:Button id='remove' Text='Remove' runat='server' OnClick='Remove_Click' class='btn btn-primary btn-lg'></asp:Button>";
                    cart.InnerHtml += "</div>";
                    cart.InnerHtml += "</div>";

How can I make an asp:button or an equivalent feature from the code behind when I don't know how many I am going to need?

1

There are 1 best solutions below

0
JobesK On

You can created anything from code behind. If looking at your ondatabound event something like:

 //placeHolderLink is the ID of the placeholder control, create instance
 PlaceHolder ph = ((PlaceHolder)e.Row.FindControl("placeholderLink"));


 // create a link button and add what ever attributes you need
 LinkButton link = new LinkButton();
 link.Text = "x"; //delete 


 // add link button control to place holder
  ph.Controls.Add(link);