I find myself needing to preform the same actions on both HtmlControls and WebControls. I am a firm believer in DRY and find the fact that there is only the Control class to use if I want to consolidate the functions on both types. The problem that I have with using Control is that there certain properties that both HtmlControl and WebControl expose that Control does not. In the current case, the Attributes property is the problem. Does anyone have any suggestions on how to avoid the duplication of code in this type of instance?
Both HtmlControl and WebControl implement the interface IAttributeAccessor (explicitly). Use the IAttributeAccessor.SetAttribute instead. I'm not a vb.net coder, so I leave the task of writing the code to the reader. ;)
In the past I've duplicated code to set the attributes for HtmlControls and WebControls. However, here's another idea:
Private Sub SetAttribute(ByRef ctrl As Control, ByVal key As String, ByVal value As String)
If TypeOf ctrl Is HtmlControl Then
DirectCast(ctrl, HtmlControl).Attributes(key) = value
ElseIf TypeOf ctrl Is WebControl Then
DirectCast(ctrl, WebControl).Attributes(key) = value
End If
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
For Each ctrl In Me.Controls
SetAttribute(ctrl, "class", "classname")
Next
End Sub
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With