Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1449
  • Last Modified:

Maintain Listbox attributes on postback

I have duel listboxes. One for Unselected and  One for Selected. I color the individual items based on a value from the dataset. The problem is that the listbox doesn't maintain its attributes on postback. :( So when a button is clicked to move an item from one box to the other the color attribute is lost.  Is their a way to save listitem's color attribute ? Even if I have to readd them then do a check to color the second listbox. something like :
For i = ListView1.Items.Count - 1 To 0 Step -1
            If ListView1.Items(i).ForeColor = Color.Red Then   'moving red only
            End If

Haha..Any help would be appreciated.:D
'Here's how I set the color originally:
If ds.Tables(0).Rows.Count >0 then
   with ListBox1
     .DataSource = ds
     .DataTextField = "name"
     .DataValueField = "someValue"
     Dim i as Interger
    For i = 0 to ds.Tables(0).Rows.Count -1
       If da.Tables(0).Rows(i)("anotherValue") = True Then
         .Items(i).Attributes.Add("style", "color:blue")
          .Items(i).Attributes.Add("style", "color:red")
      end if
   end with
end if

Open in new window

  • 3
3 Solutions
Unfortunetly ListBox items will not retain custom attributes.  The easiest thing i can thing of is build an array of the attribute values and store it in viewstate.  The index of the attibute would correspond to the index of the item in the listbox.
wht1986 is right, as I, too, have recently banged my head against this limitation. Depending on your situation, you might find it easiest to just rebind on every postback.
did that solve your problem middletownRI?
MiddletownRIAuthor Commented:
These didn't really solve my problem. wht1986 was close in theory.
I eventually had to create a custom user control that derives from the listbox.
It saves all the attributes and recreates them on init.
Still have some issues though. So I'd say, no not solved yet.
Is there no good solution to this issue with listbox attributes and holding value on postback?
Nope nothing out of the box that i know of.  Either a custom control where you save to the control state or add to your page (UserControl) something like:

public List<string> MyListBoxAttributes
    get {return ViewState("MyListBoxAttributes");}
    set {ViewState("MyListBoxAttributes") = value;

then when you need attribute of item #3 its just MyListBoxAttributes[3]

You would set the List whenever you created the listbox items or on the databound event


Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now