Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically change / set checkedListBox item fore colour

I have code below. How can i set checkedListBox item fore colour depending on if item is checked or not checked?

private void FindSelectedUserRoles()
{
        lblSelectedUser.Text = Code.CommonUtilities.getDgvStringColValue(dataGridViewUserList, "UserName").Trim();

        //iterate all roles selected user is member of
        for (int i = 0; i < checkedListRoles.Items.Count; i++)
        {
            string roleName = checkedListRoles.Items[i].ToString();
            string selectedUserRoles = Code.MemberShipManager.GetSpecificUsersRoles(lblSelectedUser.Text.Trim());

            if (selectedUserRoles.Contains(roleName))
            {
                checkedListRoles.SetItemChecked(i, true);
                //here i want to set item fore colour to green

            }
            else if (selectedUserRoles.Contains(roleName) == false)
            {
                checkedListRoles.SetItemChecked(i, false);
                //and here, i want item fore colour to remain black
            }
        }
}
like image 320
StackTrace Avatar asked Jul 11 '13 08:07

StackTrace


1 Answers

Since it's rather complicated to draw the thing yourself, you could actually let the original control draw itself -- just tweaking the color. This is my suggestion:

public class CustomCheckedListBox : CheckedListBox
{
    protected override void OnDrawItem(DrawItemEventArgs e)
    {
        Color foreColor;
        if (e.Index >= 0)
        {
            foreColor = GetItemChecked(e.Index) ? Color.Green : Color.Red;
        }
        else
        {
            foreColor = e.ForeColor;
        }

        // Copy the original event args, just tweaking the fore color.
        var tweakedEventArgs = new DrawItemEventArgs(
            e.Graphics,
            e.Font,
            e.Bounds,
            e.Index,
            e.State,
            foreColor,
            e.BackColor);

        // Call the original OnDrawItem, but supply the tweaked color.
        base.OnDrawItem(tweakedEventArgs);
    }
}
like image 105
Mattias Larsson Avatar answered Sep 22 '22 18:09

Mattias Larsson