error checking using bool and radiobuttons - c#

I'd like to implement some error checking on my program.
If properties have not been selected my program should throw up an error message instructing the user to input the missing information.
I've implemented this for some properties but the final part which deals with radio buttons and bools is causing me trouble.
private void btnAddPatient_Click(object sender, RoutedEventArgs e)////Adds Patients using buttone etc to set properties
{
string name = txtPatientName.Text,bloodType;
int 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 == "" || rbA.IsChecked.Equals(false) || rbB.IsChecked.Equals(false) || rbAB.IsChecked.Equals(false) || rb0.IsChecked.Equals(false))
{
if (txtPatientName.Text == "")
{
MessageBox.Show("Please enter Patient's Name");
}
else if (dpDOB.SelectedDate == null)
{
MessageBox.Show("Please select a date");
}
else if (rbA.IsChecked.Equals(false) || rbB.IsChecked.Equals(false) || rbAB.IsChecked.Equals(false) || rb0.IsChecked.Equals(false))
{
MessageBox.Show("Please enter patient's blood type");
}
}
else
{
if (bloodA)
{
bloodType = "A";
}
else if (bloodB)
{
bloodType = "B";
}
else if (bloodAB)
{
bloodType = "AB";
}
else
{
bloodType = "0";
}
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();
}
}

You already got the values captured in the blood# variables, so you may use one of these approaches:
Using the variables for your if statement:
if (!(bloodA || bloodB || bloodAB || blood0))
MessageBox.Show("Please enter patient's blood type");
Using a list (just one more line):
List<bool> rbValues = new List<bool>() { bloodA, bloodB, bloodAB, blood0 };
if (!rbValues.Any(b => b))
MessageBox.Show("Please enter patient's blood type");
Or making it reusable within your method, as you use it for other evaluations:
var anyBlood = (bloodA || bloodB || bloodAB || blood0)
...
if (dpDOB.SelectedDate == null || txtPatientName.Text == "" || !anyBlood)
...
if (!anyBlood)
MessageBox.Show("Please enter patient's blood type");
Hope it helps

Related

C# Character count condition

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.

checkbox only one allowed, code not working [duplicate]

This question already has answers here:
Only one checkbox to be selected
(6 answers)
Closed 6 years ago.
I am struggling with why my code is not working. This is for a school assignment. I am allowed to ask for help. I am new to programming. I am using visual studio 2015. I am trying to get it so the user must only be allowed to select one checkbox. I have other checkboxes in this assignment so using last checked will not work. I am not getting errors, it just does nothing. Thanks!
My checkBoxes are named checkBox1, checkBox2,......5
My entire current code is:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Chapter6Homework
{
public partial class IceCreamOrder : Form
{
public IceCreamOrder()
{
InitializeComponent();
}
private void btn_Clear_Click(object sender, EventArgs e)
{
// Clear flavors by automatically selecting default button on Clear button click
rdbDefault.Checked = true;
// Clear toppings
checkBox_CookieDough.CheckState = CheckState.Unchecked;
checkBox_ChocolateSyrup.CheckState = CheckState.Unchecked;
checkBox_Marshmallows.CheckState = CheckState.Unchecked;
checkBox_OreoPieces.CheckState = CheckState.Unchecked;
checkbox_Sprinkles.CheckState = CheckState.Unchecked;
checkbox_Walnuts.CheckState = CheckState.Unchecked;
// Clear List Box
lstDisplay.Items.Clear();
// Clear scoops
checkBox1.CheckState = CheckState.Unchecked;
checkBox2.CheckState = CheckState.Unchecked;
checkBox3.CheckState = CheckState.Unchecked;
checkBox4.CheckState = CheckState.Unchecked;
checkBox5.CheckState = CheckState.Unchecked;
}
private void btn_CalculateCost_Click(object sender, EventArgs e)
{
// Verify user selected a flavor
if (rdbDefault.Checked == true)
{
MessageBox.Show("Please select a flavor");
return;
}
// Verify user seleted # of scoops
if (checkBox1.CheckState == CheckState.Unchecked &&
checkBox2.CheckState == CheckState.Unchecked &&
checkBox3.CheckState == CheckState.Unchecked &&
checkBox4.CheckState == CheckState.Unchecked &&
checkBox5.CheckState == CheckState.Unchecked)
{
MessageBox.Show("You must select a number of scoops. 1 is a must but 5 is recommended!");
return;
}
//Verify user got the toppings they wanted if any
if (checkBox_ChocolateSyrup.CheckState == CheckState.Unchecked &&
checkBox_CookieDough.CheckState == CheckState.Unchecked &&
checkBox_Marshmallows.CheckState == CheckState.Unchecked &&
checkBox_OreoPieces.CheckState == CheckState.Unchecked &&
checkbox_Sprinkles.CheckState == CheckState.Unchecked &&
checkbox_Walnuts.CheckState == CheckState.Unchecked)
{
DialogResult dr = MessageBox.Show("Are you sure you don't want toppings?",
"help", MessageBoxButtons.YesNo);
switch (dr)
{
case DialogResult.Yes: break;
case DialogResult.No: return;
}
}
// Declare Variables and constants
double flavorCost = FlavorCost();
double toppingCost = ToppingCost();
double scoops = Scoops() * flavorCost;
double subTotal = (flavorCost + toppingCost + scoops);
double salesTax = subTotal * .08;
double total = subTotal + salesTax;
// Display total price of order
lstDisplay.Items.Clear();
lstDisplay.Items.Add("Total: " + total.ToString("C2"));
// Display total sales tax
lstDisplay.Items.Add("");
lstDisplay.Items.Add("Sales Tax: " + salesTax.ToString("C2"));
// Display Flavor Cost
lstDisplay.Items.Add("Flavor: " + flavorCost.ToString("C2"));
// Display Scoops Cost
lstDisplay.Items.Add("Scoops: " + scoops.ToString("C2"));
// Display Toppings
lstDisplay.Items.Add("Toppings: " + toppingCost.ToString("C2"));
}
// Get flavor cost
Double FlavorCost()
{
if ((radioButton_Chocolate.Checked == true) || (radioButton_Strawberry.Checked == true))
return 1.5F;
else if (radioButton_Vanilla.Checked == true)
return 1.25F;
else
return 0;
}
// Get num of scoops
Double Scoops()
{
if (checkBox1.Checked == true)
return 1;
else if (checkBox2.Checked == true)
return 2;
else if (checkBox3.Checked == true)
return 3;
else if (checkBox4.Checked == true)
return 4;
else if (checkBox5.Checked == true)
return 5;
else
return 0;
}
// Get Toppings
Double ToppingCost()
{
if ((checkBox_ChocolateSyrup.Checked == true) ||
(checkBox_Marshmallows.Checked == true) ||
(checkbox_Sprinkles.Checked == true))
return .25F;
else if ((checkBox_OreoPieces.Checked == true) ||
(checkBox_CookieDough.Checked == true) ||
(checkbox_Walnuts.Checked == true))
return .50F;
else
return 0;
}
private void IceCreamOrder_Load_1(object sender, EventArgs e)
{
//Set Default to true on load
rdbDefault.Checked = true;
}
internal class Sub
{
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
int numberChecked = 0;
CheckBox[] array = new
CheckBox[] { checkBox1, checkBox2, checkBox3, checkBox4, checkBox5 };
for (int i = 0; i < array.Length; i++)
{
if
(array[i].Checked)
numberChecked++;
else if
(numberChecked > 1)
MessageBox.Show("You have checked "
+ numberChecked.ToString() + " checkBoxes. Only one is allowed.");
else
return;
}
}
}
}
Use RadioButton with grouping.
To make your solution work: ( sender is the selected checkbox )
private void checkBox1_Checked(object sender, EventArgs e)
{
var array = new CheckBox[] { checkBox1, checkBox2, checkBox3, checkBox4, checkBox5 };
foreach(var checkbox in array)
{
if(checkbox != sender){
checkbox.IsChecked = false
}
}

How to check two conditions in an IF statement in windows phone 7 application using c#?

I am building an application for windows phone 7 where i have a form and i need to validate two conditions here. The condition is that the textbox shouldnot contain null value and also the value should not be equal to *Name.
if(name.Text == String.Empty)
{
MessageBox.Show("Please Enter the name");
name.Focus();
return false;
}
Please help me to put the 2nd condition here
if ((name.Text == String.Empty) || (name.Text == "Name"))
{
MessageBox.Show("Please Enter the name");
name.Focus();
return false;
}
You want to use the && operator, something like this
if (name.Text == String.Empty && name.Text != *Name)
{
MessageBox.Show("Please Enter the name");
name.Focus();
return false;
}
you need OR condition like below
if (string.IsNullOrEmpty(name.Text) || name.Text == "Name")
{
MessageBox.Show("Please Enter the name");
name.Focus();
return false;
}
try this:
if (name.Text == null && name.Text != "Name")
{
MessageBox.Show("Please Enter the name");
name.Focus();
return false;
}
if ((name.Text == String.Empty) || (name.Text == "Name"))
{
MessageBox.Show("Please Enter the name");
name.Focus();
return false;
}
if (name.Text == String.Empty)
{
MessageBox.Show("Please Enter the name");
name.Focus();
return false;
}
else
{
if(name.Text == "Name"){
MessageBox.Show("Your error message");
name.Focus();
return false;
}
}

Write to text files

Totally new to this. Depending on which event button I click I need to write to the appropriate text file. However, the input data writes to the same text file. How do I specify the appropriate text file it writes to and is saved.
The coding, identical apart from the name of the text file, I'm currently using is:
private void btnItemAdd_Click(object sender, EventArgs e)
{
string sItem;
string sNumber;
if (rdoDrinks.Checked == false && rdoConfectionary.Checked == false)
{
//Message to remind user to select category
MessageBox.Show("Please select a category");
txtItem.Focus();
}
{
{
if ((rdoDrinks.Checked == true) && (txtItem.Text != "") && (txtItemNumber.Text == ""))
//Message to remind user to enter a number
MessageBox.Show("Please input a number");
txtItemNumber.Focus();
if ((txtItem.Text != "") && (txtItemNumber.Text != ""))
{
//add Item to end of list
lstItems.Items.Add(string.Format("{0, -15} {1, -20}", txtItem.Text, txtItemNumber.Text));
txtCount.Text = lstItems.Items.Count.ToString();
//set focus to the text box
txtItem.Focus();
StreamWriter sw = File.AppendText("Drinks.txt");
{
sItem = txtItem.Text;
sw.WriteLine(sItem);
sNumber = txtItemNumber.Text;
sw.WriteLine(sNumber);
}
MessageBox.Show("Details have been saved");
txtItem.Clear();
txtItemNumber.Clear();
sw.Close();
}
else if ((rdoConfectionary.Checked == true) && (txtItem.Text != "") && (txtItemNumber.Text == ""))
//Message to remind user to enter a number
MessageBox.Show("Please input a number");
txtItemNumber.Focus();
if ((txtItem.Text != "") && (txtItemNumber.Text != ""))
{
//add Item to end of list
lstItems.Items.Add(string.Format("{0, -15} {1, -20}", txtItem.Text, txtItemNumber.Text));
txtCount.Text = lstItems.Items.Count.ToString();
//set focus to the text box
txtItem.Focus();
StreamWriter sw = File.AppendText("Confectionary.txt");
{
sItem = txtItem.Text;
sw.WriteLine(sItem);
sNumber = txtItemNumber.Text;
sw.WriteLine(sNumber);
}
MessageBox.Show("Details have been saved");
txtItem.Clear();
txtItemNumber.Clear();
sw.Close();
}
}
}
}
You have several issues:
You are missing an else after the first if.
The code below can never end up being true.
The two if statement collide (the txtItemNumber.Text comparison is the problem). Hence you will never end up writing to Drinks.txt:
if ((rdoDrinks.Checked == true) && (txtItem.Text != "") && (txtItemNumber.Text == ""))
...
if ((txtItem.Text != "") && (txtItemNumber.Text != ""))

Hide/Show radio buttons on a questionnaire application

I am doing an assignment involving the creation of a simple Quiz type form application. However, whenever I run the program, only the first answer shows for a multiple question and I cannot for the life of me figure out why.
This is the contstructor:
MultipleChoice dlg =
new MultipleChoice(
new Question("What is the capital of Zimbabwe?",
new Answer("Paris", false),
new Answer("Washington D.C.", false),
new Answer("Harare", true),
new Answer("Cairo", false),
new Answer("N'Djamena", false)));
if (dlg.ShowDialog() == DialogResult.OK)
{
if (dlg.Correct) MessageBox.Show("You got something right!");
else MessageBox.Show("You couldn't be more wrong");
}
And this is the Question Form Code:
private Question Q;
public MultipleChoice (Question q)
{
Q = q;
InitializeComponent();
textPrompt.Text = Q.Prompt;
if (Q.A != null)
{
radioA.Text = Q.A.Prompt;
}
else radioA.Hide();
if (Q.B != null)
{
radioB.Text = Q.B.Prompt;
}
radioB.Hide();
if (Q.C != null)
{
radioC.Text = Q.C.Prompt;
}
radioC.Hide();
if (Q.D != null)
{
radioD.Text = Q.D.Prompt;
}
radioD.Hide();
if (Q.E != null)
{
radioE.Text = Q.E.Prompt;
}
radioE.Hide();
}
public bool Correct
{
get
{
if (Q == null) return false;
if (Q.A != null && Q.A.Correct && radioA.Checked) return true;
if (Q.B != null && Q.B.Correct && radioB.Checked) return true;
if (Q.C != null && Q.C.Correct && radioC.Checked) return true;
if (Q.D != null && Q.D.Correct && radioD.Checked) return true;
if (Q.E != null && Q.E.Correct && radioE.Checked) return true;
return false;
}
}
Where have I gone wrong?
There is no else for any option after A:
if (Q.B != null)
{
radioB.Text = Q.B.Prompt;
}
radioB.Hide(); //This is **always** going to be called - hiding radioB :)
Should be:
if (Q.B != null)
radioB.Text = Q.B.Prompt;
else
radioB.Hide();

Categories