开发者

Sending an array as a server tag's property

I am wondering if it's possible to send an开发者_开发问答 array of strings to a tag's property

<SampleTag:Form 
  runat="server"  
  ID="sampleform1"
  Items={item1,item2,item3,item4}
>
</SampleTag:Form>

This doesn't work since it sends "{item1,item2,item3,item4}" as a string to the class.


Better off doing this in code behind

<SampleTag:Form runat="server" ID="sampleform1"></SampleTag:Form>

sampleform1.Items = new { item1, item2, item3, item4 };


You may have to add attributes to your property but you should be able to continue using the xml side to perform the assignment:

<SampleTag:Form
  runat="server"
  ID="sampleform1">

    <Items ID="item1">item1</Items>
    <Items ID="item2">item2</Items>
    <Items ID="item3">item3</Items>
    <Items ID="item4">item4</Items>

</SampleTag>

This article might provide some extra insight: http://msdn.microsoft.com/en-us/library/aa478964.aspx


I know you already accepted an answer, but I wanted to let you know it's possible to do what you are trying to do using a type converter. I prefer this method as it makes the control more designer friendly and easier for others to use.

Use: (sorry for the VB code...)

<cc1:ServerControl1 ID="ServerControl11" runat="server" Items="Testing,Test2,Test3,Test4,Test5" />

Code:

The key is the use of the TypeConverter attribute on the property (see after this class for the definition).

Public Class ServerControl1
    Inherits WebControl

    <TypeConverter(GetType(StringToArray))> _
    Public Property Items() As String()
        Get
            If ViewState("Items") IsNot Nothing Then
                Return ViewState("Items")
            Else
                Return New String() {}
            End If
        End Get
        Set(ByVal value As String())
            ViewState("Items") = value
        End Set
    End Property

    Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter)
        MyBase.Render(writer)

        For Each s As String In Items
            writer.Write(String.Format("-{0}<br/>", s))
        Next
    End Sub
End Class

Public Class StringToArray
    Inherits TypeConverter

    Public Overloads Overrides Function CanConvertFrom(ByVal context As ITypeDescriptorContext, ByVal sourceType As Type) As Boolean
        If sourceType Is GetType(String) Then
            Return True
        End If
        Return MyBase.CanConvertFrom(context, sourceType)
    End Function

    Public Overloads Overrides Function ConvertFrom(ByVal context As ITypeDescriptorContext, ByVal culture As CultureInfo, ByVal value As Object) As Object
        If TypeOf value Is String Then
            Dim v As String() = CStr(value).Split(New Char() {","c})
            Return v
        End If
        Return MyBase.ConvertFrom(context, culture, value)
    End Function
End Class
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜