Search code examples
c#checkboxmessagebox

Call a CheckBox's Text to a MessageBox?


Hello I'm having trouble trying to get this part of my code working:

 private void selectedBox(string text)
    {
        var boxes = new Control[] { f1.checkEdit7, f1.checkEdit8, f1.checkEdit9 };
        foreach (var box in boxes)
        {
            if(box.Checked == true)
            {
                text = box.Text.ToString();
            }
        }
    }

I want to be able to get the selected checkbox's text and call it in a MessageBox, how would I achieve this? Thank you!


Solution

  •   private List<string> selectedBoxes()
        {
            List<string> checkBoxText = new List<string>();
            var boxes = new CheckBox[] { checkBox1, checkBox2, checkBox3 };
            foreach (var box in boxes)
            {
                if (box.Checked == true)
                {
                    checkBoxText.Add(box.Text);
    
                }
            }
            return checkBoxText;
        }
        public void ShowMessage()
        {
            var selectedCheckboxes = selectedBoxes();
            MessageBox.Show(string.Join(",", selectedCheckboxes));
        }
    

    The biggest change was using the more specific Checkbox class which inherits from Checkbox -> ButtonBase => control. With the more specific class you get functionality geared towards checkboxes instead of controls in general.