Search code examples
c#formsvalidationcheckboxtabular

How to Implement a Table with scale within?


I would like to have a Form with a table in it. The first row will describe a Scale. In each cell in the table, there will be a a checkBox button, that will have my choice. (only one can be chosen (validation))

              **1**             **2**           **3**
a)______________checkBoxbttn_____________________   checkBoxbttn____________________              V

b)     ____________  checkBoxbttn___________________________        V        ___________________      checkBoxbttn

After marking only one checkBox in every row (validation), I'll need to save each row's choose in a parameter, for future use. For the example above: int a = 3; int b = 2;

How can I implement that? How the validations looks like?


Solution

  • I suggest you to use a TableLayoutPanel with one column and any number of rows. In each cell, place a Panel. In each panel, place three RadioButton controls, to ensure that only one among those is selected.

    To know which RadioButton is selected, you can iterate through each Panel's controls and returning the first one checked.

    Example:

    private void button1_Click(object sender, EventArgs e)
        {
            foreach (var row in tableLayoutPanel1.Controls)
            {
                var panel = row as Panel;
                if (panel == null) continue;
                var checkedButton = 
                    panel.Controls.OfType<RadioButton>()
                        .FirstOrDefault(r => r.Checked);
                if (checkedButton == null) continue;
                //Process your radiobutton here.
            }
        }
    

    To assign a specific value to a RadioButton, I would create a class deriving from it, with a property representing your value.

    Example:

    class ScaleRadioButton : RadioButton
    {
        public int MyScale { get; set; }
    }