Friday 13 November 2009

Adding User Controls programmatically

If you haven't come across this problem yet when developing webforms projects then trust me, at some point you are going to.

Scenario

You have a view product page in a shopping cart application which has an "add to cart" button which adds one of these products to a shopping basket.
Your client comes along and says they want users not to have to drill down to the product detail page to add products to their baskets. So you are
now faced with having to work out how you will add an add to cart button to each product summary. Here's how you could deal with this problem.

1. Create a user control which displays a product summary and maybe call it something like displayProduct.ascx

2. User Controls are classes so expose a property or properties within the code behind file

For example let's say your Product Class has an ID property you could set your user control to have a productID property like this:


Private _productID As Integer

Public Property productID() As Integer
Get
Return _productID
End Get
Set(ByVal value As Integer)
_productID = value
End Set
End Property


2.a. take the add to cart button functionality from your product detail page and replicate it in your user control. So you might add a button called
AddToCart and code something like:

Protected Sub AddToCart_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles AddToCart.Click
Dim c As New Cart
Dim p As New Product
p = p.GetProductByID(me._productID)
c.AddProductToCart(p)
.... etc
End Sub

3. Add a placeholder control to your new product listings page to contain the user controls.

4. Now for the clever bit, let's say you have a ProductManager class which returns a list of Product class instances which you can pass into your
user controls, you can then loop through this list and add a displayProduct.ascx user control for each Product in your list. The code might look something
like this:



Public Sub DisplayHandsets()
Dim pm As New ProductManager
Dim pl As New List(Of Product)
pl = pm.GetProducts
Dim p As Product
For Each p In pl
'add user control for each product
Dim dp As displayProduct = CType(LoadControl("displayProduct.ascx"), displayProduct)
dp.productID = p.ID
' add the user control to your placeholder
phProducts.Controls.Add(dp)
Next
End Sub

5. Give yourself a big pat on the back for doing some serious nerd kung fu!

No comments: