I have several radioButtons stored in two different strings.
I need them printed bound together on a label. How can I do it?
private void Button_Click(object sender, RoutedEventArgs e)
{
String cad1 = null;
String cad2 = null;
if (rad1.IsChecked == true)
{
cad1 = "Ok";
}
else if (rad2.IsChecked == true)
{
cad1 = "Ok Cancel!";
}
else if (rad3.IsChecked == true)
{
cad1 = "Yes No";
}
else if (rad4.IsChecked == true)
{
cad1 = "Yes No Cancel";
}
else if (rad5.IsChecked == true)
{
cad1 = "Retry Cancel";
}
else if (rad6.IsChecked == true)
{
cad1 = "Abort Retry Cancel";
}
else if (rad7.IsChecked == true)
{
cad2 = "Information";
}
else if (rad8.IsChecked == true)
{
cad2 = "Exclamation";
}
else if (rad9.IsChecked == true)
{
cad2 = "Question";
}
else if (rad10.IsChecked == true)
{
cad2 = "Error";
}
I need to print the result of these two strings, but for the moment, the second string is not printed
cad1 = cad1 + cad2;
lab2.Content = cad1;
}
}
The reason is all of your cad2 variables are contained in else if statements.
Modify the line
else if (rad7.IsChecked == true)
to be
if (rad7.IsChecked == true)
EDIT
I would also recommend removing all == true, they are unnecessary.
If the cad1 and cad2 aren't being used after this event I'd recommend creating a single string variable and appending the values that would have been cad1 and cad2 to it.
var cont = "";
if (rad1.IsChecked) cont += "Ok";
...
if (rad7.IsChecked) cad2 += "Information";
...
lab2.Content = cont;
Elsif only get s evaluated if the first if was not true, so if cad1 gets a value, cad2 never gets a value.
Furthermore, if (rad9.IsChecked == true) is exacttly the same as `if (rad9.IsChecked)'
And finally, if you're using an up-to-date version of C# you can use the ternaty operator:
var cad1 = rad1.IsChecked
? "Ok"
: rad2.IsChecked
? "Ok Cancel!"
: rad3.IsChecked
? "Yes No"
: rad4.IsChecked
? "Yes No Cancel"
: rad5.IsChecked
? "Retry Cancel"
: rad6.IsChecked
? "Abort Retry Cancel"
: null;
var cad2 = rad7.IsChecked
? "Information"
: rad8.IsChecked
? "Exclamation"
: rad9.IsChecked
? "Question"
: rad10.IsChecked
? "Error"
: null;
Or, if you like it more concise:
var cad1 = rad1.IsChecked ? "Ok"
: rad2.IsChecked ? "Ok Cancel!"
: rad3.IsChecked ? "Yes No"
: rad4.IsChecked ? "Yes No Cancel"
: rad5.IsChecked ? "Retry Cancel"
: rad6.IsChecked ? "Abort Retry Cancel"
: null;
var cad2 = rad7.IsChecked ? "Information"
: rad8.IsChecked ? "Exclamation"
: rad9.IsChecked ? "Question"
: rad10.IsChecked? "Error"
: null;
Now, I wonder if rad1-10 are radiobuttons, and why I cannot see in the name which ones belong to the same group. I hope 1-6 are in one and 7-10 are in another group, but better naming would avoid confusion and possible mistakes...
In your if-else chain you never set values for both cad1 and cad2 so you never get the correct output.
Te easieset way to get what you want is to split the chain to look llike this
...
else if (rad6.IsChecked == true)
{
cad1 = "Abort Retry Cancel";
}
if (rad7.IsChecked == true)
{
cad2 = "Information";
}
...
Related
I want to convert below condition to ternary
if (!string.IsNullOrEmpty(objModel.Status))
{
if (objModel.Status == "0")
{
Model.Sort = "Result1";
}
else if (objModel.Status == "8")
{
Model.Sort = "Result2";
}
else
{
Model.Sort = "Result3";
}
}
I have tried as below but it went upto if and else not else if
Model.Sort = !string.IsNullOrEmpty(Model.Status)
? (Model.Status == "0" ? Retult1 : string.Empty)
: string.Empty;
Keep a local variable for simplification
var x = objModel.Status;
if (string.IsNullOrEmpty(x))
{
Model.Sort = x=="0" ? "Result1" :
x=="8" ? "Result2" :
"Result3";
}
you can have ternary operator like this
a ? b : c ? d : e
to get this:
if (a) {
b
}
else if (c) {
{
d
}
else {
e
}
in your case
objModel.Status == "0" ? Model.Sort = "Result1" : objModel.Status == "8" ? Model.Sort = "Result2" : Model.Sort = "Result2";
I hope this helps.
You can write your code using ternary operators like this:
Model.Sort = string.IsNullOrEmpty(objModel.Status) // if (string.IsNullOrEmpty(Status))
? Model.Sort // Model.Sort = Model.Sort;
: objModel.Status == "0" // else if (Status == "0")
? "Result1" // Model.Sort = "Result1";
: objModel.Status == "8" // else if (Status == "8")
? "Result2" // Model.Sort = "Result2";
: "Result3"; // else Model.Sort = "Result3";
Where the first condition represents the if condition, and then each statement after a : operator that is a comparison represents an else if, and finally the result after the last : represents the final else assignment.
The first condition is kind of a "dummy" condition (because if it's true nothing really changes*), but is required if we want to include the IsNullOrEmpty check in the ternary operations, since the ternary operator has to return a value in both the true and false cases.
I'm not sure if the dummy assignment would get optimized away or if the setter is called in that "dummy" case. If the setter is called then potentially this could have a different effect than your original code, depending on what the setter code does.
So if I use OR statement like this:
if (option1 == true || option2 == true)
{
Print("would like to print the option that triggered above");
}
How do I figure out which option out of these 2 has been triggered?
Thanks
You can do it using else if condition.
E.g.:
if(option1 && !option2)
{
//Option 1
}else if(!option1 && option2)
{
//option 2
}else if(option1 && option2)
{
//both
}
else
{
//no option
}
I'm sorry but you can't.
But instead you can split the if statement
if (option1 == true)
{
Print("option1 is true");
}
if (option2 == true)
{
Print("option2 is true");
}
or put additional checks inside of the if statement(but it's useless).
if(option1 == true || option2 == true){
if (option1 == true)
{
Print("option1 is true");
}
if (option2 == true)
{
Print("option2 is true");
}
}
also you can use
if(option1){}
instead of
if(option1 == true){}
oh, and you could also use this to check if both are true
if (option1 == true && option2 == true)
{
Print("both options are true");
}
if (option1 == true || option2 == true)
{
if(option1)
Print("Option 1");
else
Print("Option2");
}
You could possibly get in dangerous water, though, as you might end up with a situation where option1 == true and option2 == true.
If you really need to know which one was triggered, I would suggest you branch out. if(option1 == true) { ... } else if(option2 == true) { ... } else { ... }.
You could also do this:
if(option1 == true || option2 == true) {
if(option1 == true) {}
if(option2 == true) {}
}
You'd have to test them both again inside the if statement.
Note the short circuit 'or' statement you have used (||). So if option1 one is true, it wont test the second condition.
if (option1 == true || option2 == true)
{
if (option1 == true)
{
Print("option1");
}
else
{
Print("option2");
}
}
You can not find which statement is trigger in your code, you need 2 statements
if (option1 == true || option2 == true)// statement 1
{
Print( option1 ? "option 1 triggered above" : "option 2 triggered above");// statement 2
}
how can i put condition here. Like if i Inputted a 4 digit character, it'll put a Prefix which is "F-".
try
{
Service1 ws = new Service1();
if (e.KeyChar == (char)13 && button1.Enabled == true)
{
inputtxt = F.Text.ToString();
showpic(inputtxt);
if (ws.VerifyEID(inputtxt) == false)
{
MessageBox.Show("You have entered an incorrect Employee ID. Please try again!", "Attendance Monitoring System", MessageBoxButtons.OK, MessageBoxIcon.Warning);
F.Text = null;
}
else
{
panel1.Visible = false;
SqlToText(inputtxt);
ShowOffset(inputtxt);
if (BtnTimeIn.Visible == true)
{
BtnTimeIn.Focus();
}
else
{
BtnTimeOut.Focus();
}
}
}
Help me please, thankyou.
You can insert this in your code:
inputtxt = inputtxt.StartsWith("F-") ? inputtxt : "F-" + inputtxt;
But I would personally have that prefix on the textbox to make it clear for the users what to type in and have them type less characters.
Hi have have an if statement inside the event of a button, when i run the code and select the first radio and click on the button(which does the calculations) it prints it out on the label, but when i click on the second radio button and click the button to calculate the answer nothing happens at all. Any ideas please
private void button1_Click(object sender, EventArgs e)
{
if (radioButton1.Checked == true)
{
double a; // have to declare double here as we cannot include it below as bool is a rue or false statment
bool success1 = double.TryParse(textBox1.Text, out a); // take in value as true or false
if (success1) // check if it was parsed successful
{
label4.Text = ConvertToCel(a).ToString(); // now set it in label
}
else if (radioButton1.Checked == false && radioButton2.Checked == true)
{
double a1;
bool success = double.TryParse(textBox1.Text, out a1);
if (success){
label3.Text = ConvertToFar(a1).ToString();
}
}
else if (radioButton1.Checked == false && radioButton2.Checked == false)
{
label4.Text = "Please select an option from above";
}
}
}�
The problem is that you are checking for the condition of radiobutton1 being checked first and then nested other conditions inside it, so if the first condition is false the other conditions are not being checked, so to avoid that you should bring the other else if-conditions outside the first if-condition, you can use:-
private void button1_Click(object sender, EventArgs e)
{
double a; // have to declare double here as we cannot include it below as bool is a rue or false statment
bool success1 = double.TryParse(textBox1.Text, out a); // take in value as true or false
if (radioButton1.Checked == true)
{
if (success1) // check if it was parsed successful
{
label4.Text = ConvertToCel(a).ToString(); // now set it in label
}
}
else if (radioButton1.Checked == false && radioButton2.Checked == true)
{
if (success)
{
label3.Text = ConvertToFar(a).ToString();
}
}
else if (radioButton1.Checked == false && radioButton2.Checked == false)
{
label4.Text = "Please select an option from above";
}
}
That's because radio buttons are mutually exclusive, and you are only executing the code if radioButton1 is checked. You should probably also handle the case where the textbox could not be parsed correctly (i.e. if the user enters something that cannot be converted to a double). I've included this below.
double a;
bool success = double.TryParse(textBox1.Text, out a);
if (success)
{
if (radioButton1.Checked == true)
{
label4.Text = ConvertToCel(a).ToString();
}
else if (radioButton2.Checked == true)
{
label3.Text = ConvertToFar(a).ToString();
}
else
{
label4.Text = "Please select an option from above";
}
}
else
{
label4.Text = "The value could not be convered to a number.";
}
That's because you have put the else on the if statement inside the first if statement. The checks for radiobutton 2 will only be run if the condition in the first if statement is true.
End the block for the first if statement before the else statements:
private void button1_Click(object sender, EventArgs e)
{
if (radioButton1.Checked == true)
{
double a; // have to declare double here as we cannot include it below as bool is a rue or false statment
bool success1 = double.TryParse(textBox1.Text, out a); // take in value as true or false
if (success1) // check if it was parsed successful
{
label4.Text = ConvertToCel(a).ToString(); // now set it in label
}
}
else if (radioButton1.Checked == false && radioButton2.Checked == true)
{
double a1;
bool success = double.TryParse(textBox1.Text, out a1);
if (success){
label3.Text = ConvertToFar(a1).ToString();
}
}
else if (radioButton1.Checked == false && radioButton2.Checked == false)
{
label4.Text = "Please select an option from above";
}
}
My code is like this
string statuscodeToSet;
if (xElementAltItem != null && (generalstatuscode.Contains(currentstatuscode) && xElementAltItem.Value.Trim() =="null"))
{
statuscodeToSet = "1";
}
if (xElementupdateDate != null && (xElementAltItem != null && (generalstatuscode.Contains(currentstatuscode) && xElementAltItem.Value.Trim() == "null") && xElementupdateDate.Value == "01-JAN-2099"))
{
statuscodeToSet = "2";
}
if (xElementupdateDate != null && (xElementAltItem != null && (generalstatuscode.Contains(currentstatuscode) && xElementAltItem.Value.Trim() == "null") && xElementupdateDate.Value != "01-JAN-2099"))
{
statuscodeToSet = "3";
}
if (xElementAltItem != null && (generalstatuscode.Contains(currentstatuscode) && xElementAltItem.Value.Trim() != "null"))
{
statuscodeToSet = "4";
}
if (xElementAltItem != null && (currentstatuscode == "Act-NotOrd" && xElementAltItem.Value.Trim() == "null"))
{
statuscodeToSet = "5";
}
Obviously I don't think this is the best way to code this.Is there any way I can shorten this code and looks it more standard. May be using Linq
This seems to be the simplest possible, but I don't think this is simple.
if (xElementAltItem != null)
{
if (xElementAltItem.Value.Trim() == "null")
{
if (generalstatuscode.Contains(currentstatuscode))
{
statuscodeToSet = "1";
if (xElementupdateDate != null)
{
if (xElementupdateDate.Value == "01-JAN-2099")
{
statuscodeToSet = "2";
}
if (xElementupdateDate.Value != "01-JAN-2099")
{
statuscodeToSet = "3";
}
}
}
if ((currentstatuscode == "Act-NotOrd"))
{
statuscodeToSet = "5";
}
}
else
{
if (generalstatuscode.Contains(currentstatuscode))
{
statuscodeToSet = "4";
}
}
}
You really need to tease out the logic here by creating some meaningful variable names to make the conditions read like English otherwise your code is vulnerable to bugs.
Update: I seem to have introduced a difference wrt the original in the handling of the update date as it appears I collapsed three states into two (whoops!) which appears in steps #2/#3. In any case, I believe the following is still an applicable template to follow.
Step #1: Eliminate the duplicate conditional checks with variables.
This simplifies the conditionals greatly and makes it easier to see what is "supposed" to happen.
var nullAlt = xElementAltItem != null ? xElementAltItem.Value.Trim() == "null" : false;
var hasCurrentStatus = generalstatuscode.Contains(currentstatuscode);
var updateDate = xElementupdateDate != null ? xElementupdateDate.Value : "";
if (nullAlt && hasCurrentStatus)
{
statuscodeToSet = "1";
}
if (nullAlt && hasCurrentStatus && updateDate == "01-JAN-2099"))
{
statuscodeToSet = "2";
}
if (nullAlt && hasCurrentStatus && updateDate != "01-JAN-2099"))
{
statuscodeToSet = "3";
}
if (!nullAlt && hasCurrentStatus)
{
statuscodeToSet = "4";
}
if (nullAlt && currentstatuscode == "Act-NotOrd")
{
statuscodeToSet = "5";
}
Step #2: Group the separate conditions and rewrite the code with "nested" and "else" conditionals.
This should eliminate most (if not all) of the duplicate checks and provide "one path" through the entire conditional structure. The order of grouping depends upon the logical importance of each condition and how well it eliminates duplicates between branches. In this case the code is grouped by nullAt and then hasCurrentState.
// ..
if (nullAlt) {
if (hasCurrentStatus) {
statuscodeToSet = "1";
if (updateDate == "01-JAN-2099"))
{
statuscodeToSet = "2";
} else { /* updateDate != "01-JAN-2099" */
{
statuscodeToSet = "3";
}
} else if (currentstatuscode == "Act-NotOrd")
{
statuscodeToSet = "5";
}
} else { /* !nullAlt */
if (hasCurrentStatus)
{
statuscodeToSet = "4";
}
}
Step #3: Place the code into a separate function and return the result.
That is, don't assign the "status" to a variable. Besides maintaining tidy code separation and self-documentation, this is useful because then invalid code paths/logic can be more easily spotted.
For instance, return "1" makes no sense where it is located (as then neither status "2" nor "3" could be reached and if it removed then status "1" is never returned!) and there are some "otherwise" cases not handled.
string GetStatusCode (..) {
// ..
if (nullAlt) {
if (hasCurrentStatus) {
// whoops! What was this doing??
return "1";
if (updateDate == "01-JAN-2099"))
{
return "2";
} else { /* updateDate != "01-JAN-2099" */
{
return "3";
}
} else if (currentstatuscode == "Act-NotOrd")
{
return "5";
} else {
// return what here?
}
} else { /* !nullAlt */
if (hasCurrentStatus)
{
return "4";
} else {
// return what here?
}
}
}
At this final stage, the usage of the intermediate variables could be reverted without losing much readability because the duplicate expressions have been eliminated. However, excepting in cases where lazy evaluation is strictly required, separate variables are perfectly valid - use them if they make the code cleaner.
Using enumerations or constants would also be an improvement: a status value of NeedsUpdate is more informative than "3".
I recommend keeping it simple and following the approach outlined above.
YMMV.
Try this:
if (xElementAltItem == null)
return;
statuscodeToSet = "1";
if (xElementAltItem.Value.Trim() == "null")
if (generalstatuscode.Contains(currentstatuscode))
statuscodeToSet = xElementupdateDate != null && xElementupdateDate.Value != "01-JAN-2099" ? "3" : "2";
statuscodeToSet = currentstatuscode == "Act-NotOrd" ? "5" : null;
else
statuscodeToSet = generalstatuscode.Contains(currentstatuscode) ? "4" : null;