Csharp Checked List Box Test
I want to make a Checked List Box where only some of the values are clickable. Imagine clicking the screenshot below and not being able to toggle the gray items:
Make Checked, Unchecked and Indeterminate checks
I obviously want some items grayed out - so this little helper populates the list.
private void FillIt(int n) { for (int i = 0; i < n; i++) if (i % 3 == 0) checkedListBox1.Items.Add(new intCarrier(i), CheckState.Checked); else if (i % 3 == 1) checkedListBox1.Items.Add(new intCarrier(i), CheckState.Unchecked); else checkedListBox1.Items.Add(new intCarrier(i), CheckState.Indeterminate); }
The constructor is thus:
public ClbTestForm() { InitializeComponent(); FillIt(8); }
Add not just an Event Handler: add an Item Check Event Handler
I first did this by turning off toggle on click and (SelectionMode was set to None) and then making a custom event handler upon click. But that was no good. With a little help from our friends at Microsoft [1] I instead inserted an Item Check Event Handler (read more at [2]). This way we can still toggle the values we should be able to toggle with for example the keyboard.
this.checkedListBox1.CheckOnClick = true; this.checkedListBox1.ItemCheck += new System.Windows.Forms.ItemCheckEventHandler (this.checkedListBox1_ItemCheck);
Control the values
I want a user to be able to toggle only the ones that are not Indetermined (recall that the check state property can be Checked, Unchecked or Indeterminate: [3]). So I replace any new value with the old one of the old one was indeterminate.
void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e) { if (e.CurrentValue == CheckState.Indeterminate) e.NewValue = e.CurrentValue; }
Download
Download code here [4] and executable here [5]
Belongs in Kategori Programmering.