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
I found myself needing to perform the same operation on HtmlControls and WebControls. I firmly believe in DRY and I found that if I want to combine functions on the two types, only the Control class can be used. The problem I encountered when using Control is that both HtmlControl and WebControl expose certain attributes that Control does not have. In the current situation, the Attributes attribute is Question. Does anyone have any suggestions on how to avoid code duplication in such instances?
In the past, I copied the code to set the properties of HtmlControls and WebControls. However, this is 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< br />End Sub