C# 如何使从groupbox中选择的单选按钮显示在标签中?
当用户从组框中的单选按钮中选择一个选项以显示在标签中时,是否有一种方法 它将在C# 如何使从groupbox中选择的单选按钮显示在标签中?,c#,radio-button,label,groupbox,C#,Radio Button,Label,Groupbox,当用户从组框中的单选按钮中选择一个选项以显示在标签中时,是否有一种方法 它将在numberPhoneTextBox.Text后面的线路上显示数量/电话类型 共有3个单选按钮供用户选择 private void displayButton_Click(object sender, EventArgs e) { summaryLabel.Text = "Receipt Summary\n" + "--------------\n" + "Name: " + n
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 + "/";
}
不幸的是,你必须用手来做。您可以定义执行任务的方法或属性,以避免重复代码,如下所示:
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
顺便说一句,你应该摆脱使用字符串连接的习惯。效率很低。相反,请尝试以下方法:
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);
}
测试了它,你的方式工作。但是我刚刚检查了项目分配,它不允许使用if/else语句。。真可惜。要做到这一点还有很长的路要走?谢谢你的帮助!我已经编辑了你的标题。请参阅“”,其中的共识是“不,他们不应该”。