ASP.NET – How to perform the same operation on WebControls and HTMLControls

I found that I need to perform the same operations on HtmlControls and WebControls. I firmly believe in DRY and found that if I want to combine functions on both types, only the Control class can be used. I use The problem encountered in Control is that both HtmlControl and WebControl expose certain attributes that Control does not have. In the current situation, the Attributes attribute is the problem. 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: < p>

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

Leave a Comment

Your email address will not be published.