Search code examples
c#radio-buttonlabelgroupbox

How to make a radio button selection from groupbox appear in a label?


Is there a way when a user selects a choice from a radio button from a group-box to appear in a label?

It would be on the line with Quantity/Phone Type right after numberPhoneTextBox.Text.

There are a total of 3 radio-buttons for the user to choose from.

private void displayButton_Click(object sender, EventArgs e)
{
    summaryLabel.Text = "Receipt Summary\n" +
        "--------------\n" +
        "Name: " + nameTextBox.Text +
        "\nAddress: " + streetTextBox.Text +
        "\nCity: " + cityTextBox.Text +
        "\nState: " + stateTextBox.Text +
        "\nZip Code: " + zipTextBox.Text +
        "\nPhone Number: " + phoneNumberTextBox.Text +
        "\nDate: " + dateMaskedBox.Text +
        "\n-------------------------" +
        "\nQuantity/Phone Type: " + numberPhoneTextBox.Text + "/";
}

Solution

  • You would have to do it by hand, unfortunately. You could define a method or property that performs the task for you to avoid repetitive code, like so:

    String GetRadioButtonValue() {
             if( radioButton1.Checked ) return radioButton1.Text;
        else if( radioButton2.Checked ) return radioButton2.Text;
        else                            return radioButton3.Text;
    }
    

    UPDATE:

    Apparently the OP's assignment "doesn't allow the user of if/else statements" - that's quite surreal, but you can skirt it several ways, such as using the ?: operator:

    String GetRadioButtonValue() {
        return radioButton1.Checked ? radioButton1.Text
             : radioButton2.Checked ? radioButton2.Text
                                    : radioButton3.Text;
    }
    

    Another option is to use events:

    private String _selectedRadioText;
    
    public MyForm() { // your form's constructor
        InitializeComponent();
        radioButton1.CheckedChanged += RadioButtonCheckedChanged;
        radioButton2.CheckedChanged += RadioButtonCheckedChanged;
        radioButton3.CheckedChanged += RadioButtonCheckedChanged;
        // or even:
        // foreach(Control c in this.groupBox.Controls)
        //     if( c is RadioButton )
        //         ((RadioButton)c).CheckedChanged += RadioButtonCheckedChanged;
    
        // Initialize the field
        _selectedRadioText = radioButton1.Text;
    }
    
    private void RadioButtonCheckedChanged(Object sender, EventArgs e) {
        _selectedRadioText = ((RadioButton)sender).Text;
    }
    
    // then just concatenate the _selectedRadioText field into your string