Home > database >  Display an alert message if a checkbox is uncheck C#
Display an alert message if a checkbox is uncheck C#

Time:06-12

I'm trying to create a design form in visual studio with 4 checkboxes and I really want to make the user to check only one of them, and if he's not checked one, when he will press a button, he should receive a notification with the obligation to select a box, and the program should not starting.

CodePudding user response:

RadioGroup is a control very similar in appearance to CheckBox. It's used to select only one RadioGroup in each group. You can define groups of radio buttons puttin inside a container (a Form, a Panel, a GroupBox). Add 4 radio buttons to your form, set the Text property.

You can check if a radio button is selected:

var isChecked = radioButton1.Checked;

Or make a method like this:

private int GetSelectedRadioIndex()
{
    var buttons = new[]
    {
        this.radioButton1,
        this.radioButton2,
        this.radioButton3,
        this.radioButton4
    };
    for (int i = 0; i < buttons.Length; i  )
    {
        if (buttons[i].Checked)
        {
            return i;
        }
    }

    return -1;
}

If you get a <0 index, there aren't a radio selected. In other case you have a 0 index of the radio that is selected.

CodePudding user response:

As indicated, use a container like a Panel or GroupBox while with a GroupBox you can set a caption to indicate what the RadioButtons are for.

Create a private list in the form

private List<RadioButton> _radioButtons;

Subscribe to the Form's OnShown event, add the following code where OptionsGroupBox is a GroupBox with four Radio Buttons. This ensures no default selection which is optional.

private void OnShown(object sender, EventArgs e)
{
    _radioButtons = OptionsGroupBox.Controls.OfType<RadioButton>().ToList();
    _radioButtons.ForEach(rb => rb.Checked = false);
}

Add a button to assert/get their selection.

private void CheckSelectionButton_Click(object sender, EventArgs e)
{
    var selection = _radioButtons.FirstOrDefault(x => x.Checked);
    if (selection == null)
    {
        MessageBox.Show("Make a selection");
    }
    else
    {
        MessageBox.Show($"You selected {selection.Text}");
    }
}
  • Related