I have 3 pair of radiobutton at my form I want to check at every group of radiobutton one radiobutton is checked when user press save button. I used the below code to check every radiobutton, but I think this one a better approach to check.
if (radioBttnAddrssCoYes.Checked || rdoBttnAddCorrectNo.Checked)
{
if (rdoGroundFloorTrue.Checked || radioGroundFFalse.Checked)
{
if (rdoHomeTrue.Checked || radioMeet.Checked)
{
// Here I do something
}
else
{
MessageBox.Show("Please check Customer All day At Home");
}
}
else
{
MessageBox.Show("Please Check Ground Floor Delivery");
}
}
else
{
MessageBox.Show("Check Addresss Correct");
}
Thanks For your support and help
I would probably do it a little different, but it doesn't mean your way is wrong.
if(VaildateRadioGroupIsChecked(radioBttnAddrssCoYes, rdoBttnAddCorrectNo, "Check Addresss Correct") &&
VaildateRadioGroupIsChecked(rdoGroundFloorTrue, radioGroundFFalse, "Please Check Ground Floor Delivery") &&
VaildateRadioGroupIsChecked(rdoHomeTrue, radioMeet, "Please check Customer All day At Home"))
{
// do your thing...
}
private bool VaildateRadioGroupIsChecked(RadioButton a, RadioButton b, string MessageToUser)
{
if(!a.Checked && !b.Checked) {
Messagebox.Show(MessageToUser);
return false;
}
return true;
}
Of course, you can develop it further and not send the 2 radio buttons to the function, but it's containing element. this way, if you have 3, 4, or n radio buttons you can check all of them in one simple call.
Another well known technique to validate that a radio box is checked is to simply hold a boolean variable on the form level that is false by default, and changed to true when any of the radio buttons is checked. However, this technique will not serve you well in this case, since you will need 3 boolean variables for that, and the code will be unnecessary complicated comparing to the other solutions.
To answer your question in the comment, I would probably do something like that:
string MessageToUser = VaildateRadioGroupIsChecked(radioBttnAddrssCoYes, rdoBttnAddCorrectNo, "Check Addresss Correct") +
VaildateRadioGroupIsChecked(rdoGroundFloorTrue, radioGroundFFalse, "Please Check Ground Floor Delivery") +
VaildateRadioGroupIsChecked(rdoHomeTrue, radioMeet, "Please check Customer All day At Home");
if(MessageToUser.Length == 0) {
// do your stuff
} else {
Messagebox.Show(MessageToUser);
}
private string VaildateRadioGroupIsChecked(RadioButton a, RadioButton b, string MessageToUser)
{
if(!a.Checked && !b.Checked) {
return MessageToUser + "\n";
}
return string.Empty;
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments