A question posed by @Ramsharma1234 on Twitter this morning asked how to implement Factory Patterns in ASP.NET.
(definition of Factory Pattern)
Below is what would be considered a very basic form of Factory Pattern. This method will essentially instantiate a generic Object, which is the parent of all types of Objects, and later be treated as if it were the type of child object that is used as a parameter in calling the method. On a Web site where I needed to build Web controls dynamically, based on values from a database query, I created a method called “AddControl” that would add a generic Object to a Placeholder on my Web form:
Private Sub AddControl(ByVal oControl As Object)
Placeholder1.Controls.Add(oControl)
End Sub
To call this method, I would instantiate a Web control such as a Button and add it to the Placeholder with the method:
Dim btnPrint As New Button
btnPrint.Attributes.Add("onclick", "javascript:window.print();")
btnPrint.Visible = False
AddControl(btnPrint)
Any type of Web control (TextBox, Label, Literal, etc.) could be instantiated and then added using this method. For instance, if the table value for a particular field indicated the creation of a TextBox, this would be how that could be accomplished:
Dim oControl As New Object
'...
oControl = New TextBox
With oControl
.ID = strFieldName & "_mltxt"
.TextMode = TextBoxMode.MultiLine
.MaxLength = 2000
.Style("overflow") = "hidden"
.Height = 300
.Width = 500
.BorderStyle = BorderStyle.None
.Enabled = True
.ReadOnly = True
End With
AddControl(oControl)