Search code examples
c#winformsvisual-studio-2010comboboxcheckbox

select one value of checkboxCombobox


i am using several checkboxcomboboxes. for my sollution one of these boxes needs to behave as a combobox in a specific situation. i need to select one value only. i tried the following:

    private void PreDefSerials_SelectedValueChanged(object sender, EventArgs e)
    {
        if (!one_select)
            return;
        else
        {
            // set selected value
            if (PreDefSerials.SelectedIndex != 0)
            PreDefSerials.CheckBoxItems[PreDefSerials.SelectedIndex].CheckState = CheckState.Checked;
            return;
        }
    }

EDTI:

how can i set all the checkstateds of the items to not-selected and aftwerwards make the checkstate of the latest selected value to selected?


Solution

  • I'm not familiar with that control, so I might not have all of the syntax correct, but I think you can try looping through your items and "unchecking" anything that was checked. Also, you would have to turn "off" the event for the time being or else this event would probably keep firing on every "uncheck":

    private void PreDefSerials_SelectedValueChanged(object sender, EventArgs e)
    {
      if (!one_select)
        return;
      else
      {
        if (PreDefSerials.SelectedIndex > -1)
        {
          //only uncheck items if the current item was checked:
          if (PreDefSerials.CheckBoxItems[PreDefSerials.SelectedIndex].CheckState == CheckState.Checked)
          {
            // stop firing event for now:
            PreDefSerials.SelectedValueChanged -= PreDefSerials_SelectedValueChanged;
    
            for (int i = 0; i < PreDefSerials.CheckBoxItems.Count; i++)
            {
              if (i != PreDefSerials.SelectedIndex)
              {
                PreDefSerials.CheckBoxItems[i].CheckState = CheckState.Unchecked;
              }
            }
    
            // wire event again:
            PreDefSerials.SelectedValueChanged += PreDefSerials_SelectedValueChanged;
          }
        }
      }
    }
    

    This assumes that when you check an item, it will get checked and fire this event. This code just goes through the list and then "unchecks" everything else. Refactor as needed.