I was wondering how you make a CheckBox
unselectable in c#? I thought it would be something like SetSelectable (false) or something but I can\'t seem to see th
You can set AutoCheck property to false
.
For disabling all the checkboxes in a CheckedListBox
for (int i = 0; i < checkedListBoxChecks.Items.Count; i++)
{
checkedListBoxChecks.SetItemChecked(i, true);
//checkedListBoxChecks.Enabled = false;
this.checkedListBoxChecks.SetItemCheckState(i, CheckState.Indeterminate);
}
private void checkedListBoxChecks_ItemCheck(object sender, ItemCheckEventArgs e)
{
if (e.CurrentValue == CheckState.Indeterminate)
{
e.NewValue = e.CurrentValue;
}
}
In order to make a more read-only behavior:
CheckBox
We can inherit the CheckBox
class (similar to Haris Hasan's answer but with some improvements):
public class ReadOnlyCheckBox : CheckBox
{
[System.ComponentModel.Category("Behavior")]
[System.ComponentModel.DefaultValue(false)]
public bool ReadOnly { get; set; } = false;
protected override void OnMouseEnter(EventArgs e)
{
// Disable highlight when the cursor is over the CheckBox
if (!ReadOnly) base.OnMouseEnter(e);
}
protected override void OnMouseDown(MouseEventArgs e)
{
// Disable reacting (logically or visibly) to a mouse click
if (!ReadOnly) base.OnMouseDown(e);
}
protected override void OnKeyDown(KeyEventArgs e)
{
// Suppress space key to disable checking/unchecking
if (!ReadOnly || e.KeyData != Keys.Space) base.OnKeyDown(e);
}
}
This code worked for me:
public class CtrlCheckBoxReadOnly : System.Windows.Forms.CheckBox
{
[Category("Appearance")]
[Browsable(true), EditorBrowsable(EditorBrowsableState.Always)]
public bool ReadOnly { get; set; }
protected override void OnClick(EventArgs e)
{
if (!ReadOnly) base.OnClick(e);
}
}