Newbie: how to add click function to a dynamically created Buttonin WebApplication?

T

teddy

I am trying to create a bookstore WebApplication using c#. I can
display the books (obtained from sql server) on a table in the WebForm
application. At the end of each row, I would like to add "add to cart"
button. Therefore, I use

Button bt_add = new Button();
bt_add.Text = "Add to cart";

and put it in each cell which is later added to a table row. The
Buttons display fine on the WebForm. However, I don't know how to add
the Button_Click function for each of the Buttons I created since I
don't know the total number of books returned by the database in
advance. Can anyone help me get "add to cart" button to work?

Note: I try clicking on each Button, the WebForm page loads back to its
original stage (Page_Load function) and my search result is gone.

Thanks,
 
C

Chad Z. Hower aka Kudzu

teddy said:
and put it in each cell which is later added to a table row. The
Buttons display fine on the WebForm. However, I don't know how to add
the Button_Click function for each of the Buttons I created since I
don't know the total number of books returned by the database in
advance. Can anyone help me get "add to cart" button to work?

Adding a dynamic Click event is just like in Winforms. You need to add a
delegate using +=



--
Chad Z. Hower (a.k.a. Kudzu) - http://www.hower.org/Kudzu/
"Programming is an art form that fights back"

Make your ASP.NET applications run faster
http://www.atozed.com/IntraWeb/
 
C

Corbin

Teddy,

Have you tried using template columns in a datagrid control? You can
put a hyperlink inside the template and point it to the current page,
but also as a parameter in the url pass the id of the item to be added
to the cart. Put the code to add to the cart in the Page_Load event.
I hope that makes sense--it's how I do this. A sketch of the code is
below.

Best of luck,
Corbin

sample code
--------------------------------------------------
<asp:datagrid runat="server">
<Columns>
<asp:TemplateColumn>
<ItemTemplate>
<asp:HyperLink runat="server" NavigateUrl='<%#
"thispage.aspx?addtocart=" & (DataBinder.Eval(Container.DataItem,
"itemId")) %>' />
</ItemTemplate>
</asp:TemplateColumn>
etc...

then in Page Load, before loading any page data put in the C#
equivalent to this (I'm a VB guy).

Sub Page_Load

If Not (Request.Params("addtocart") Is Nothing) Then
call AddToCart(Request.Params("addtocart"))
End If
.....etc....
End Sub
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top