ReBind ListBox And Set Color

  • 2829
  • 0

ReBind ListBox And Set Color

前言

ListBox重新Bind過後,原本所選的項目狀態就會消失! 另外,如果要設定ListItem裡的Color要如何做呢?

image

研究

因為Bind過,狀態會不見,所以在Bind前要先把所選的項目記錄起來,在Bind後再重新Assign。以下為針對ListBox(單選)、CheckBoxList(多選)記錄SelectItem的方式。

    '先將選項存起來(單選)
    If IsNothing(.SelectedValue) = False Then
        ViewState("MySel") = .SelectedValue
    End If
    .DataTextField = "FUN_ITEM_NAME"
    .DataValueField = "FUN_ITEM_ID"
    .DataSource = GetDT()
    .DataBind()
    'Bind完後再Assign值
    If String.IsNullOrEmpty(ViewState("MySel")) = False Then
        .SelectedValue = ViewState("MySel")
    End If
End With


With CheckBoxList1
    '先存起來(多選)
    GetSelectCheckList()
    .DataTextField = "FUN_ITEM_NAME"
    .DataValueField = "FUN_ITEM_ID"
    .DataSource = GetDT()
    .DataBind()
    'Bind完後再Assign值
    SetSelectCheckList()
End With

''' <summary>
''' 取得所選的CheckBox的值
''' </summary>
''' <remarks></remarks>
Private Sub GetSelectCheckList()
    Dim aryResult As New ArrayList
    For Each ltItem As ListItem In CheckBoxList1.Items
        If ltItem.Selected Then
            aryResult.Add(ltItem.Value)
        End If

    Next
    ViewState("MySelList") = aryResult.ToArray(GetType(String))
End Sub

''' <summary>
''' 依viewState中的值Assign到CheckBox中
''' </summary>
''' <remarks></remarks>
Private Sub SetSelectCheckList()
    If ViewState("MySelList") Is Nothing = False Then
        For Each ltItem As ListItem In CheckBoxList1.Items
            For Each strValue As String In ViewState("MySelList")
                If ltItem.Value = strValue Then
                    ltItem.Selected = True
                    Exit For
                End If
            Next
        Next
    End If
End Sub

那要如何設定ListItem的Color呢? 可參考:www.codeproject.com/KB/webforms/ColorListBox.aspx針對個別Item加入style去設定background-color屬性即可!

Private Sub SetListItemColor(ByRef rItems As ListItemCollection)
    Dim strStyle As String = "background-color:{0}"
    '1,3,5為紅色, 2, 4, 6為綠色, 其他為blue
    For Each ltItem As ListItem In rItems
        Dim strValue As String = ltItem.Value.Replace("Fun", "")
        Dim strColor As String = String.Empty
        Select Case strValue
            Case "1", "3", "5"
                strColor = "RED"
            Case "2", "4", "6"
                strColor = "GREEN"
            Case Else
                strColor = "Yellow"
        End Select
        ltItem.Attributes.Add("style", String.Format(strStyle, strColor))
    Next
End Sub

image

image

image

附上範例程式碼:ListBoxColor.rar

Hi, 

亂馬客Blog已移到了 「亂馬客​ : Re:從零開始的軟體開發生活

請大家繼續支持 ^_^