Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform same operations on both WebControls and HtmlControls

Tags:

.net

asp.net

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?

like image 404
David Williams Avatar asked Dec 04 '25 10:12

David Williams


2 Answers

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. ;)

like image 196
sisve Avatar answered Dec 06 '25 23:12

sisve


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        
like image 21
Steve Wortham Avatar answered Dec 07 '25 01:12

Steve Wortham



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!