将样式添加到System.Web.UI.Control

wot*_*ney 2 vb.net asp.net attributes styles

我正在从数据库模式构建一大堆不同的控件.当我在后面的代码中运行控件时,我想将控件和样式(作为数据库中的字符串...例如"color:white; width:50px; height:10px;")传递给re - 功能.

这就是我认为我应该去做的事情:

 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
Run Code Online (Sandbox Code Playgroud)

不幸的是,在行"ctrl.Attributes.Add("style",StyleArr(count))"我得到一个错误:'attributes'不是'system.web.ui.control'的成员我明白错误意味着什么,但有没有人知道这方面的方法?

非常感谢,斯科特

fre*_*ler 7

你应该使用WebControl而不是Control. WebControl来自Control但包括Attributes财产.

此外,控件的"style"属性应包含一个包含由CSS分隔的CSS的字符串;.因此,将整个字符串传递到数据库中就足够了,您不需要再进行任何处理.

所以你的功能应该简单地看起来像......

Sub AddStylesToControl(ByRef ctrl As WebControl, ByVal styles As String)
    ctrl.Attributes("style") = styles
End Sub
Run Code Online (Sandbox Code Playgroud)

我已将其更改为直接设置(而不是Add),因为这将覆盖任何现有设置"style".Attributes.Add如果"style"集合中已存在,则使用将失败.