Search code examples
c#comboboxcomboboxlist

How to change color of an item in my ComboBoxList


I have a ComboBoxList which has certain items and a button beneath it. On click event, I want to change Text Color of item if that was checked (changed text color to Red or Green). But if item color has already changed (to red or green) and item has un-checked in second round, then color should revert to original. Following is the code snippet that I tried.

ASPX

<body>
    <form id="form1"
          runat="server">
        <div>
            <asp:checkboxlist runat="server"
                              EnableViewState="true"
                              id="cbl" />
            <asp:Button ID="Button1"
                        runat="server"
                        Text="Button"
                        OnClick="Button1_Click" />
        </div>
    </form>
</body>

ServerSide

protected void Button1_Click(object sender, EventArgs e)
{
    for ( int i =0; i< count; i++)
    {
        if (this.ColumnsList.Items(i).Selected)
        {
            this.ColumnsList.Items(i).Attributes.Add("style", "Color=Red;");
        }
    }
}

Error message is

Non-invocable member 'System.Web.UI.WebControls.ListControl.Items' cannot be used like a method.

What is going wrong?


Solution

  • use ForEach instead of For and try below code.

    foreach (ListItem item in this.ColumnsList.Items)
    {
        if (item.Selected)
        {
            item.Attributes.Add("style", "Color: Red");
        }
    }