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
}
}
}
I think you should try
ListView
instead of checkedListBox. It has necessary properties and could be customized as you wish. Just setCheckboxes
property totrue
, and then in your code add forecolor like that:I think you have to draw your own
CheckedListBox item
like this:If you want to set
CheckedColor
differently for each item, you have to store theCheckedColor
setting for each item (such as in a Collection) and reference theCheckedColor
usingIndex
. However I think it's a little much work to do. So if you have such a requirement, going forListView
instead would be better.Expanding on @Mattias' answer, I made this custom control to fit my needs. I needed it to have colors depending on other factors than the Checked value.
Usage:
The accepted answer worked for me but it needs modifying if you want to disable the CustomCheckedListBox.
I modified the code as follows: -
I changed the 'CheckBoxRenderer.DrawCheckBox...' line to
and then I changed the 'using (Brush brush = new SolidBrush...' line to
This caused enabling/disabling to work for me.
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: