Pass Arguments to Subroutines from a Button Control

Pass Arguments to Subroutines from a Button Control

You can use the CommandName and CommandArgument attributes of a button to submit arguments to an ASP.NET method on the server. For example, suppose you have a repeater control in a page that shows a nicely formatted list of products. You can include a button on that page that, when clicked, calls a subroutine to add the product to the user’s shopping cart.

Rather than writing functions to get the product ID and name, or query the database to get that information, you can set the Button’s CommandName property to the name of the product and its CommandArgument property to the product ID. You can even use comma-separated values if you need more than two values (although in that case it would probably make more sense to go back to the database). Here’s a simplified example just to show how it works.

First, here’s the Button code:


And here’s the server code:

   Public Sub AddToCart(sender As Object, e As CommandEventArgs)       Session("currentCart") = Session("currentCart") & _           e.CommandName & "," & e.CommandArgument & ";"   End Sub

When the user clicks the button, you can retrieve the CommandName and CommandArgument values from the CommandEventArgs parameter defined in the AddToCart method.


Share the Post: