Listbox - Change Item's Color

4. September 2011 15:32 by Mahmoud Farhat in ASP.NET, C#  //  Tags:   //   Comments (0)

If you have two collection lists one of them for parent (Main Category) and other one for child (Sub Category) and you want to display both of them in one listbox but you want the parent item take back color different than the child, the below example code is showing how to do this.  
 
//loop for parent collection list
foreach (var parentItem in objParentCollectionList)
{
   //Set all back color items with blue
   listBox1.BackColor = Color.Blue;
   //inset parent items in listbox control
   listBox1.Items.Add(new ListItem(mainItem.Name, mainItem.ID.ToString()));
 
   //Get all childs by parent ID
   objChildCollectionList = GetChildList(mainItem.ID);
   if (objChildCollectionList != null)
   {
       //loop for child collection list
       foreach (var childItem in objChildCollectionList)
       {
           ListItem listItem = new ListItem(childItem.Name, childItem.ID.ToString());
           //change back color foe each child item
           listItem.Attributes.Add("style""background-color: Azure");
           //inset child items in listbox control
           listBox1.Items.Add(listItem);
        }
    }
}
 
Note:
listbox1.BackColor = Color.Blue; it will effect on all listbox items not on specific item