0

I have a main form with a line chart that that has 10 possible series it can display. The data in these series will be entered into textboxes by the user and added to respective List<>'s, which will then be transferred index-by-index into the respective chart series.

I've set up a secondary form called Options, which I'm hoping will allow the user control over which series are displayed at any one time. I've attempted to do this using a checkedlistbox with item names matching the names of the chart series. This has worked fine, but my user has requested that only two series ever be on the chart at once to avoid confusion.

What I'm looking for is a way to program the checkedlistbox so that once two items are checked, no more can be checked until one of the existing checks has been removed. It seems a pretty simple concept, but I can't seem to find how to 'disable' the list items one by one. Here's what I have so far:

public void disableUnchecked()
{
    int checkedCount = 0; //tracks how many items are already checked

    //loop through all items in listbox
    for (int index = 0; index < chListBoxChartSeries.Items.Count; ++index)
    {
        //if item is checked
        if (chListBoxChartSeries.CheckedItems.Contains(chListBoxChartSeries.Items[index]))
        {
            //increment tracker variable
            ++checkedCount;
        }
    }

    //once loop has finished, if 2 items are checked
    if (checkedCount == 2)
    {
        //don't let anything else be checked
        //something to disable unchecked items
    }
}

I don't think I'm far off, just need to find a way to access and disable the individual items. If anyone can point me in the right direction, I'd really appreciate it!

Thanks

Mark

KeyNone
  • 8,745
  • 4
  • 34
  • 51
marcuthh
  • 592
  • 3
  • 16
  • 42
  • See : http://stackoverflow.com/questions/4368618/how-to-disable-a-checkbox-in-a-checkedlistbox – PaulF Aug 27 '15 at 11:41

1 Answers1

4
private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
{
    if (e.NewValue == CheckState.Checked && checkedListBox1.CheckedItems.Count >= 2)
        e.NewValue = CheckState.Unchecked;
}
György Kőszeg
  • 17,093
  • 6
  • 37
  • 65
  • To turn it usefull, is necessary add `checkedListBox1_ItemCheck` to `checkedListBox1.ItemCheck`, like: `checkedListBox1.ItemCheck += checkedListBox1_ItemCheck;` – Aipi Apr 22 '21 at 20:14