我需要一个int血型,以等于一个特定的值,这取决于哪个单选按钮被选中。如果任何一个bool是真的,它将使血样相等于一个特定的价值。我只是不知道如何使bool给整条血样分配一个值。有什么指示吗?
private void btnAddPatient_Click(object sender, RoutedEventArgs e)////Adds Patients using buttone etc to set properties
{
string name = txtPatientName.Text;
int bloodType,x=1;
DateTime dob;
bool bloodA = rbA.IsChecked.Equals(true);
bool bloodB = rbB.IsChecked.Equals(true);
bool bloodAB = rbAB.IsChecked.Equals(true);
bool blood0 = rb0.IsChecked.Equals(true);
if (dpDOB.SelectedDate == null || txtPatientName.Text == "" || !bloodA || !bloodAB || !bloodB || !blood0)
{
if (txtPatientName.Text == "")
{
MessageBox.Show("Please enter Patient's Name");
}
else if (dpDOB.SelectedDate == null)
{
MessageBox.Show("Please select a date");
}
else if(!bloodA || !bloodAB || !bloodB || !blood0)
{
MessageBox.Show("Please enter patient's blood type");
}
}
else
{
//bloodType How to make this equal to a value depending on what radio button is checked?
dob = dpDOB.SelectedDate.Value;
Patient patient = new Patient(name, bloodType, x, dob);
MainWindow mainWindow = Owner as MainWindow;
patients.Add(patient);
lstPatients.ItemsSource = null;
lstPatients.ItemsSource = patients;
// this.Close();
}
}发布于 2017-03-07 20:46:27
请使用if else if检查每个单选按钮是否为真,并分配适当的值。
就像这样:
else
{
//bloodType How to make this equal to a value depending on what radio button is checked?
if(bloodA)
{
bloodType = 0;
}
else if(bloodB)
{
bloodType = 1;
}
}发布于 2017-03-07 21:01:31
首先,我建议提取类型,确切地说,是enum:
// [Flags] // you may want declare enum as Flags
public enum BloodType {
O = 0,
A = 1,
B = 2,
AB = 3
}然后,可以在三元操作符的帮助下为BloodType值赋值:
BloodType bloodType =
rb0.IsChecked ? BloodType.O
: rbA.IsChecked ? BloodType.A
: rbB.IsChecked ? BloodType.B
: BloodType.AB; 如果您想获得int值,只需强制转换:
int v = (int) bloodType;
BloodType t = (BloodType) v;发布于 2017-03-07 20:52:51
如果您不是嵌套ifs的朋友,那么另一个解决方案是将int值赋给每个单选按钮的Tag属性。然后,将组框中的所有按钮分组,找出选中的按钮,最后将标记内容转换为int。
int i;
var checkedButton = groupBox1.Controls
.OfType<RadioButton>()
.FirstOrDefault(rb => rb.Checked);
if (int.TryParse(checkedButton.Tag.ToString(), out i))
{
// here's your value
}https://stackoverflow.com/questions/42657813
复制相似问题