wotney
wotney

Reputation: 1046

add a style to System.Web.UI.Control

I am building a whole bunch of different controls from a database schema. When I run through the controls in my code behind, I want to pass the control and the styles (as a string from the database... eg. "color:white;width:50px;height:10px;") to a re-usable function.

This is how I thought I should go about it :

 Sub AddStylesToControl(ByRef ctrl As Control, Styles As String)

    'split styles string by semi colon
    Dim StyleArr() As String
    Dim count As Integer
    StyleArr = Styles.Split(";")
    For count = 0 To StyleArr.Length - 1

        '//ctrl.Attributes.Add("style", "color: red;")
        ctrl.Attributes.Add("style", StyleArr(count))
    Next

End Sub

Unfortunately, on the line "ctrl.Attributes.Add("style", StyleArr(count))" I get an error: 'attributes' is not a member of 'system.web.ui.control' I understand what the error means, but does anyone know of a way around this ?

Many thanks, Scott

Upvotes: 2

Views: 4700

Answers (1)

freefaller
freefaller

Reputation: 19953

You should use WebControl rather than Control. WebControl is derived from Control but includes the Attributes property.

Also, the "style" attribute of the control should contain a single string containing the CSS delimited by ;. So passing the entire string as you have it in your database is enough, you do not need to do any more processing.

So your function should simply look something like...

Sub AddStylesToControl(ByRef ctrl As WebControl, ByVal styles As String)
    ctrl.Attributes("style") = styles
End Sub

I have changed it to a direct setting (rather than Add) as this will overwrite any existing "style". Using Attributes.Add will fail if the "style" already exists in the collection.

Upvotes: 7

Related Questions