0

当用户从组框中的单选按钮中选择一个选项以显示在标签中时,有没有办法?

它将与 Quantity/Phone Type 紧随其后numberPhoneTextBox.Text

共有 3 个单选按钮供用户选择。

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 + "/";
}
4

2 回答 2

0

不幸的是,您必须手动完成。您可以定义一个方法或属性来为您执行任务以避免重复代码,如下所示:

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

更新:

显然,OP 的分配“不允许用户使用 if/else 语句”——这很超现实,但您可以通过多种方式避开它,例如使用?:运算符:

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

另一种选择是使用事件:

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
于 2012-09-23T22:22:13.280 回答
0

顺便说一句,您应该改掉使用字符串连接的习惯。这是非常低效的。相反,尝试这样的事情:

private void displayButton_Click(object sender, EventArgs e)
{
    summaryLabel.Text =
        string.Format(
            "Receipt Summary\n--------------\nName: {0}\nAddress: {1}\nCity: {2}\nState: {3}\nZip Code: {4}\nPhone Number: {5}\nDate: {6}\n-------------------------\nQuantity/Phone Type: {7}/",
            nameTextBox.Text,
            streetTextBox.Text,
            cityTextBox.Text,
            stateTextBox.Text,
            zipTextBox.Text,
            phoneNumberTextBox.Text,
            dateMaskedBox.Text,
            numberPhoneTextBox.Text);
}
于 2012-09-24T00:33:16.093 回答