回发后,DropDownList中的ListItems属性会丢失吗?

时间:2013-04-02 09:31:32

标签: asp.net vb.net drop-down-menu postback listitem

我在dropdownlist数据绑定事件期间手动添加了一些attirubte。但是,在回发后,属性丢失。我在ListItems attributes in a DropDownList are lost on postback?找到了相关问题,我完全按照解决方案。

这就是我所拥有的

Dropdownlist数据绑定事件* .aspx.vb,我在每个listitem中添加了属性“class”

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    If Not IsPostBack Then
        ddlCountry.DataBind()
    End If
End Sub

Protected Sub ddlCountry_DataBound(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlCountry.DataBound
    Dim ddlCountryList As DropDownList = LocationBLL.GetDropDownList("Country", "C", "C", False, "")
    Dim lstPleaseSelect As ListItem = New ListItem("Please Select", "-1")
    Dim lstOthers As ListItem = New ListItem("Others", "0")

    lstPleaseSelect.Attributes("class") = "-1"
    lstOthers.Attributes("class") = "-1"

    ddlCountry.Items.Add(lstPleaseSelect)
    For Each lstItem As ListItem In ddlCountryList.Items
        lstItem.Attributes("class") = lstItem.Value
        ddlCountry.Items.Add(lstItem)
    Next
    ddlCountry.Items.Add(lstOthers)
End Sub

*。ASPX

<%@ Register TagPrefix="msjNewControls" Namespace="NewControls"%>

*。ASPX

<msjNewControls:NewDropDownList ID="ddlCountry" runat="server" AutoPostBack="False" >
</msjNewControls:NewDropDownList>

类文件* .vb

Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Security.Permissions
Imports System.Linq
Imports System.Text
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls

Namespace NewControls
<DefaultProperty("Text")> _
<ToolboxData("<{0}:ServerControl1 runat=server></{0}:ServerControl1>")> _
Public Class NewDropDownList
    Inherits DropDownList

    <Bindable(True)> _
    <Category("Appearance")> _
    <DefaultValue("")> _
    <Localizable(True)> _
    Protected Overrides Function SaveViewState() As Object
        ' create object array for Item count + 1
        Dim allStates As Object() = New Object(Me.Items.Count) {}

        ' the +1 is to hold the base info
        Dim baseState As Object = MyBase.SaveViewState()
        allStates(0) = baseState

        Dim i As Int32 = 1
        ' now loop through and save each Style attribute for the List
        For Each li As ListItem In Me.Items
            Dim j As Int32 = 0
            Dim attributes As String()() = New String(li.Attributes.Count - 1)() {}
            For Each attribute As String In li.Attributes.Keys
                attributes(System.Math.Max(System.Threading.Interlocked.Increment(j), j - 1)) = New String() {attribute, li.Attributes(attribute)}
            Next
            allStates(System.Math.Max(System.Threading.Interlocked.Increment(i), i - 1)) = attributes
        Next
        Return allStates
    End Function

    Protected Overrides Sub LoadViewState(ByVal savedState As Object)
        If savedState IsNot Nothing Then
            Dim myState As Object() = DirectCast(savedState, Object())

            ' restore base first
            If myState(0) IsNot Nothing Then
                MyBase.LoadViewState(myState(0))
            End If

            Dim i As Int32 = 1
            For Each li As ListItem In Me.Items
                ' loop through and restore each style attribute
                For Each attribute As String() In DirectCast(myState(System.Math.Max(System.Threading.Interlocked.Increment(i), i - 1)), String()())
                    li.Attributes(attribute(0)) = attribute(1)
                Next
            Next
        End If
    End Sub
End Class
End Namespace

但是我的班级文件仍然收到以下错误。

Exception Details: System.InvalidCastException: Unable to cast object of type 'System.Collections.DictionaryEntry' to type 'System.Web.UI.WebControls.ListItem'.

Source Error: 

Line 34:                     attributes(System.Math.Max(System.Threading.Interlocked.Increment(j), j - 1)) = New String() {attribute, li.Attributes(attribute)}

Source File: D:\root\App_Code\BLL\CustomDropDownListBLL.vb    Line: 34 

任何人都可以提供帮助?

1 个答案:

答案 0 :(得分:0)

我发现ddl中唯一保留的值是文本和值。 因此,我编写了以下代码,以使用户标记为高优先级的颜色编码和加粗列表项保持不变。这在SelectedIndexChanged事件中对我有用。 由于HighPriority标志存储在SQL中,因此我将ListItem文本的第一个字符设置为!。返回数据行时。另外,我发现当选择一个项目时,Forecolor属性仍然不适用,因此我使用bSetSelected标志将ForeColor根据需要设置为适当的颜色。

    Private Sub ddlYourDropDownList_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ddlYourDropDownList.SelectedIndexChanged

    Try
        'do your processing here, then reset the attributes below

        'color code high priority requests in Red
        Dim li As ListItem, bSetSelected As Boolean = False
        For Each li In ddlYourDropDownList.Items
            'see if this is a High Priority item, SQL Proc places the ! at the start of the string
            If li.Text.Substring(0, 1) = "!" Then
                li.Attributes.Add("style", "color:Red; font-weight: bold;")
                'once we set the selected one, no need to change ForeColor anymore
                If Not bSetSelected Then
                    If li.Selected Then
                        ddlYourDropDownList.ForeColor = Drawing.Color.Red
                        bSetSelected = True
                    Else
                        ddlYourDropDownList.ForeColor = Drawing.Color.Black
                    End If
                End If
            Else
                li.Attributes.Add("style", "color:Black; font-weight: normal;")
            End If
        Next


    Catch ex As Exception
        lblMessage.Text = "Error: " & ex.Message
    End Try
End Sub