My C# code is something like as follows.
if(TextBox1.Text.Length > 5)
{
if(TextBox2.Text.Length > 5)
{
if(TextBox3.Text.Length > 5)
{
if(TextBox4.Text.Length > 5)
{
//Action to pass to the next stage.
}
else
{
error4.text = "Textbox4 value should be minimum of 5 characters.";
}
}
else
{
error3.text = "Textbox3 value should be minimum of 5 characters.";
}
}
else
{
error2.text = "Textbox2 value should be minimum of 5 characters.";
}
}
else
{
error1.text = "Textbox1 value should be minimum of 5 characters.";
}
1) In the above kind of sample. I am using nested If-Else concept where on button click, if TextBox1 value is less than 5 is moves to else part and shows the error1 value but it will not check for further errors.
2) If I change If conditions to step by step If conditions then it will not work for me because the action must be done only if all the IF conditions satisfies.
3) If I use && operator to check all conditions I will not get individual error to each "error label"
How can I check multiple IF conditions on a single button click?
My original code
if (checkavail == "available")
{
if (name.Text.Length > 0)
{
if (email.Text.Length > 5)
{
if (password1.Text.Length > 7 && password1.Text == password2.Text)
{
if (alternate.Text.Contains("#") && alternate.Text.Contains("."))
{
if (question.Text.Length > 0)
{
if (answer.Text.Length > 0)
{
Response.Redirect("next_page.aspx");
}
else
{
error5.Text = "Please enter your security answer";
}
}
else
{
error4.Text = "Please enter your security question";
}
}
else
{
error3.Text = "Invaild alternate email address";
}
}
else
{
error2.Text = "Password should be minimum 8 characters and must match confirm password";
}
}
else
{
error1.Text = "Email address should be minimum 6 characters";
}
}
else
{
error.Text = "Please enter your name";
}
}
else
{
error1.Text = "This email address is already taken. Please try another";
}
I need the Redirect action to be done upon satisfying all conditions. If more than one error was found each error should get each error message.
Make a function that just handles the error messages. Return an Enumerable from this function. Then you can format your if-statements like this and it will return an Enumerable:
private IEnumerable GetErrors()
{
if (TextBox1.Text.Length > 5) { yield return "Textbox1 minimum bla bla"; }
if (TextBox2.Text.Length > 5) { yield return "Textbox2 minimum bla bla"; }
if (TextBox3.Text.Length > 5) { yield return "Textbox3 minimum bla bla"; }
}
Make another function that handles your non-error message logic and just perform an if-statement to see if there were zero errors or not:
public void DoSomething()
{
var errors = GetErrors();
if (errors.Count == 0)
Response.Redirect("next_page.aspx");
else
error.Text = "Please fix your errors";
}
Thanks to all. I found my answer in below manner
string p1, p2, p3, p4;
if (TextBox1.Text.Length > 5)
{
p1 = "pass";
Label1.Text = "";
}
else
{
Label1.Text = "Textbox1 value should be minimum 5 characters.";
p1 = "fail";
}
if (TextBox2.Text.Length > 5)
{
p2 = "pass";
Label2.Text = "";
}
else
{
Label2.Text = "Textbox2 value should be minimum 5 characters.";
p2 = "fail";
}
if (TextBox3.Text.Length > 5)
{
p3 = "pass";
Label3.Text = "";
}
else
{
Label3.Text = "Textbox3 value should be minimum 5 characters.";
p3 = "fail";
}
if (TextBox4.Text.Length > 5)
{
p4 = "pass";
Label4.Text = "";
}
else
{
Label4.Text = "Textbox4 value should be minimum 5 characters.";
p4 = "fail";
}
if (p1 == "pass" && p2 == "pass" && p3 == "pass" && p4 == "pass")
{
Status.Text = "All pass";
}
Related
I am creating an XML from a backend that is supposed to be fed into a GDSN datapool. The company has a very old backend which only has their own PLU number and barcode attached to every item. What I know is that (at least here in Iceland) most GTIN are the EAN-13 barcode with a padded 0 at the front although this is not always the case. Do you know of a library that could check if a GTIN is correct i.e. would calculate the check digit?
I am using a windows form and am using C#.
First to validate what you want to do:
https://www.gs1.org/services/check-digit-calculator
Then you have 2 possibilities for GTIN since it must be 14 digits long.
The case you described, then you pad a 0 on the left
A GTIN with right length is provided directly (which is possible and left digit will not be 0)
Here is a quick example on how you can check this, based on the fact you know the gtin string only contains digits:
public Boolean ValidateGTIN(string gtin)
{
string tmpGTIN = gtin;
if (tmpGTIN.Length < 13)
{
Console.Write("GTIN code is invalid (should be at least 13 digits long)");
return false;
}
else if (tmpGTIN.Length == 13)
{
tmpGTIN = "0" + gtin;
}
// Now that you have a GTIN with 14 digits, you can check the checksum
Boolean IsValid = false;
int Sum = 0;
int EvenSum = 0;
int CurrentDigit = 0;
for (int pos = 0; pos <= 12; ++pos)
{
Int32.TryParse(tmpGTIN[pos].ToString(), out CurrentDigit);
if (pos % 2 == 0)
{
EvenSum += CurrentDigit;
}
else
{
Sum += CurrentDigit;
}
}
Sum += 3 * EvenSum;
Int32.TryParse(tmpGTIN[13].ToString(), out CurrentDigit);
IsValid = ((10 - (Sum % 10)) % 10) == CurrentDigit;
if (!IsValid)
{
Console.Write("GTIN code is invalid (wrong checksum)");
}
return IsValid;
}
Thanks for that. This is almost there. I would like to take it a step further - I am going to copy your code and add a little:
//First create a function only for validating
//This is your code to almost all - variable names change
public Boolean validateGTIN(string gtin)
{
Boolean IsValid = false;
int Sum = 0;
int EvenSum = 0;
int CurrentDigit = 0;
for (int pos = 0; pos <= 12; ++pos)
{
Int32.TryParse(gtin[pos].ToString(), out CurrentDigit);
if (pos % 2 == 0)
{
EvenSum += CurrentDigit;
}
else
{
Sum += CurrentDigit;
}
}
Sum += 3 * EvenSum;
Int32.TryParse(GTIN[13].ToString(), out CurrentDigit);
IsValid = ((10 - (Sum % 10)) % 10) == CurrentDigit;
if (!IsValid)
{
Console.Write("GTIN code is invalid (wrong checksum)");
}
return IsValid;
}
//Here we change quite a bit to accommodate for edge cases:
//We return a string which is the GTIN fully formed or we throw and exception.
public String createGTIN(string bcFromBackend)
{
string barcodeStr = bcFromBackend;
//Here we check if the barcode supplied has fewer than 13 digits
if (barcodeStr.Length < 13)
{
throw new System.ArgumentException("Barcode not an EAN-13
barcode");
}
//If the barcode is of length 13 we start feeding the value with a padded 0
//into our validate fuction if it returns false then we pad with 1 and so on
//until we get to 9. It then throws an error if not valid
else if (barcodeStr.Length == 13)
{
if(validateGTIN("0"+ barcodeStr))
{
return "0" + barcodeStr;
}
else if(validateGTIN("1" + barcodeStr))
{
return "1" + barcodeStr;
}
else if(validateGTIN("2" + barcodeStr))
{
return "2" + barcodeStr;
}
else if(validateGTIN("3" + barcodeStr))
{
return "3" + barcodeStr;
}
else if(validateGTIN("4" + barcodeStr))
{
return "4" + barcodeStr;
}
else if(validateGTIN("4" + barcodeStr))
{
return "4" + barcodeStr;
}
else if(validateGTIN("5" + barcodeStr))
{
return "5" + barcodeStr;
}
else if(validateGTIN("6" + barcodeStr))
{
return "6" + barcodeStr;
}
else if(validateGTIN("7" + barcodeStr))
{
return "7" + barcodeStr;
}
else if(validateGTIN("8" + barcodeStr))
{
return "8" + barcodeStr;
}
else if(validateGTIN("9" + barcodeStr))
{
return "9" + barcodeStr;
} else {
throw new System.InvalidOperationException("Unable to create valid
GTIN from given barcode")
}
}
//Lastly if the barcode is of length 14 we try with this value. Else throw
//error
else if(barcodeStr.Length == 14)
{
if(validateGTIN(barcodeStr)
{
return barcodeStr;
}
else
{
throw new System.InvalidOperationException("Unable to create valid
GTIN from given barcode");
}
}
Hopefully this makes sense. I have not sent the code through testing as I don't have my IDE on my current computer installed. Is
For an internship project I'm making an app based on Foley sound effects. I made a game for it. One button generates the effect, one plays the sound and four buttons for possible awnsers.
Somehow, the text displays ('helaas' and 'juist!') aren't consistent. The awnser could be right and it will display 'helaas', but when clicken multiple times, it will display 'juist!'. Can anyone help me with what I am doing wrong here?
int kiesnummer()
{
Random randomSound = new Random();
int theSound = randomSound.Next(1, 4);
return theSound;
}
NewSound.Click += delegate
{
kiesnummer();
if (kiesnummer() == 1)
{
welk.Text = "Open haard";
}
else if (kiesnummer() == 2)
{
welk.Text = "Regen";
}
else if (kiesnummer() == 3)
{
welk.Text = "Hondenpootjes op hout";
}
else if (kiesnummer() == 4)
{
welk.Text = "Paardenhoeven op beton";
}
};
Play.Click += delegate
{
if (kiesnummer() == 1)
{
_chips.Start();
}
else if (kiesnummer() == 2)
{
_rain.Start();
}
else if (kiesnummer() == 3)
{
_doggo.Start();
}
else if(kiesnummer() == 4)
{
_koko.Start();
}
};
//Parameters aan functie koppelen bij klikken op de knop
Aw1.Click += delegate
{
kiesknop(1);
};
Aw2.Click += delegate
{
kiesknop(2);
};
Aw3.Click += delegate
{
kiesknop(3);
};
Aw4.Click += delegate
{
kiesknop(4);
};
//Beoordelen of keuze juist of onjuist is
bool kiesknop(int knop)
{
if (knop == kiesnummer())
{
end.Text = "Juist!";
return true;
}
else
{
end.Text = "Helaas!";
return false;
}
}
(I left the button and media declerations out, since it didn't seem relevant)
Calling kiesnummer(); in every if condition will give you different results as it generates new random value every time.
Call it once and use its value through-out:
int value = kiesnummer();
if (value == 1)
{
welk.Text = "Open haard";
}
else if (value == 2)
{
welk.Text = "Regen";
}
else if (value) == 3)
{
welk.Text = "Hondenpootjes op hout";
}
else if (value == 4)
{
welk.Text = "Paardenhoeven op beton";
}
I'm trying to make an int equal to a certain value if a condition is true.
I'm having trouble getting the bloodtype int from the if statement so it can be applied to my class. I know its probably a simple solution but my brain is fried.
private void btnAddPatient_Click(object sender, RoutedEventArgs e)////Add Patients
{
string name = txtPatientName.Text;
int bloodType,age=30;
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 == ""||bloodType==0)
if (dpDOB.SelectedDate == null || txtPatientName.Text == "" || !bloodA || !bloodAB || !bloodB || !blood0)
{
if (txtPatientName.Text == "")
{
MessageBox.Show("Please enter Patient's Name");
}
else if (!bloodA || !bloodAB || !bloodB || !blood0)
{
MessageBox.Show("Please enter patient's blood type");
}
//else if (dpDOB.SelectedDate == null)
//{
// MessageBox.Show("Please select a date");
//}
}
else
if (bloodA)
{
bloodType = 0;
}
else if (bloodB)
{
bloodType = 1;
}
else if (bloodAB)
{
bloodType = 2;
}
else {
bloodType = 3;
dob = dpDOB.SelectedDate.Value;
Patient patient= new Patient(name, age, bloodType);///cant get bloodtype value
MainWindow mainWindow = Owner as MainWindow;
patients.Add(patient);
lstPatients.ItemsSource = null;
lstPatients.ItemsSource = patients;
// this.Close();
}
The place you want the bloodType will only be evaluated if all other conditions fails as you use a if else if structure. Futhermore, you assign it to 3 prior passing it to the constructor of Patient. Therefore, at the moment this code is evaluated, bloodType will be equal to 3.
try something like
int bloodtype = -1;
(or some other value you won't use otherwise). the variable only gets set inside the if else statements, so you can't send it to your Patient class since it doesn't equal anything outside of the conditionals.
You need to invert your bloodType condition and also take your patient creation out from the blood type 3 check block:
private void btnAddPatient_Click(object sender, RoutedEventArgs e)////Add Patients
{
string name = txtPatientName.Text;
int bloodType,age=30;
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);
var bloodTypeDefined = bloodA || bloodAB || bloodB || blood0;
// if (dpDOB.SelectedDate == null || txtPatientName.Text == ""||bloodType==0)
if (dpDOB.SelectedDate == null || txtPatientName.Text == "" || !bloodTypeDefined)
{
if (txtPatientName.Text == "")
{
MessageBox.Show("Please enter Patient's Name");
}
else if (!bloodTypeDefined)
{
MessageBox.Show("Please enter patient's blood type");
}
//else if (dpDOB.SelectedDate == null)
//{
// MessageBox.Show("Please select a date");
//}
}
else
{
if (bloodA) bloodType = 0;
else if (bloodB) bloodType = 1;
else if (bloodAB) bloodType = 2;
else bloodType = 3;
dob = dpDOB.SelectedDate.Value;
Patient patient= new Patient(name, age, bloodType);///cant get bloodtype value
MainWindow mainWindow = Owner as MainWindow;
patients.Add(patient);
lstPatients.ItemsSource = null;
lstPatients.ItemsSource = patients;
}
// this.Close();
}
i have a form with more than one NumericUpDown as controls to input answer. i want every input is true for an operation (multiplication, sum etc), NumericUpDown for that operation will be disable. i have used the code below (just for sum operation), but i think its not efficient because i have to make a method to check every operation.
private void IsSumTrue() {
if (add1 + add2 == sum.Value)
{
sum.Enabled = false;
}
}
private void IsDifferenceTrue()
{
if (add1 - add2 == difference.Value)
{
difference.Enabled = false;
}
}
private void IsProductTrue()
{
if (add1 * add2 == product.Value)
{
product.Enabled = false;
}
}
private void IsQuotientTrue()
{
if (add1 / add2 == quotient.Value)
{
quotient.Enabled = false;
}
}
anyone have idea how to make it more efficient with just a method for all operation?
below is my idea, but to check the value is true for every NumericUpDown i don't know how.
private void DisableIfValueIsTrue()
{
foreach(Control control in this.Controls)
{
NumericUpDown value = control as NumericUpDown;
// if(value [NEED HELP]
}
}
Considering your situtaion, you can set a tag for each NumericUpDown in design mode like this:
sum.Tag=1;
square.Tag=2;
etc
Then define some int variables:
int iSum=add1+add2;
int iSquare= //Whatever you want
etc
And finally loop through your controls this way:
foreach (NumericUpDown control in this.Controls.OfType<NumericUpDown>())
{
int intCondition = Convert.ToInt32(control.Tag) == 1
? iSum
: Convert.ToInt32(control.Tag) == 2
? iSquare
: Convert.ToInt32(control.Tag) == 3
? i3
: i4; //You should extend this for your 8 controls
control.Enabled = intCondition == control.Value;
}
OK! Second way I offer
Since you will have to always check 8 different conditions, you could simply forget about looping through the controls and just change your method like this:
private void DisableIfValueIsTrue()
{
sum.Enabled = add1 + add2 != sum.Value;
difference.Enabled= add1 - add2 != difference.Value;
product.Enabled= add1 * add2 != product.Value;
quotient.Enabled= (add2 !=0) && (add1 / add2 != quotient.Value);
//etc
}
I came across this while doing some research and would like to give my solution I used for my situation and hope it helps people. I needed minimum and maximum numbers for a calculation, so mine are named appropriately and I correlated these with some CheckBoxes. I used null in beginning of minimum and end of maximum to account for empty. I also had to create an event handler SubscribeToEvents() shown below.
In my load event for my form:
SubscribeToEvents();
_checkBoxs = new[] { cbXLight, cbLight, cbMedium, cbHeavy, cbXHeavy, cbXXHeavy, cbXXXHeavy };
_minimumsNumericUpDowns = new[] { null, nLightMin, nMediumMin, nHeavyMin, nXHeavyMin, nXXHeavyMin, nXXXHeavyMin };
_maximumsNumericUpDowns = new[] { nXLightMax, nLightMax, nMediumMax, nHeavyMax, nXHeavyMax, nXXHeavyMax, null };
then I created a method:
private void DisableNumericUpDowns()
{
// disable everything:
foreach (var n in _minimumsNumericUpDowns)
{
if (n != null)
n.Enabled = false;
}
foreach (var n in _maximumsNumericUpDowns)
{
if (n != null)
n.Enabled = false;
}
}
The event handler:
private bool _eventsSubscribed;
private void SubscribeToEvents()
{
if (_eventsSubscribed)
return;
_eventsSubscribed = true;
cbXXHeavy.CheckedChanged += CheckBox_NumericState;
cbXHeavy.CheckedChanged += CheckBox_NumericState;
cbXLight.CheckedChanged += CheckBox_NumericState;
cbHeavy.CheckedChanged += CheckBox_NumericState;
cbLight.CheckedChanged += CheckBox_NumericState;
cbMedium.CheckedChanged += CheckBox_NumericState;
cbXXXHeavy.CheckedChanged += CheckBox_NumericState;
}
Now I can used this to check when they are enabled and if they are greater than or less than 0 if needed in the method CheckBox:
private void CheckBox_NumericState(object sender, EventArgs e)
{
// disable everything
DisableNumericUpDowns();
// see if more than one checkbox is checked:
var numChecked = _checkBoxs.Count((cb) => cb.Checked);
// enable things if more than one item is checked:
if (numChecked <= 1) return;
// find the smallest and enable its max:
var smallest = -1;
for (var i = 0; i < _checkBoxs.Length; i++)
{
if (!_checkBoxs[i].Checked) continue;
if (_maximumsNumericUpDowns[i] != null)
{
_maximumsNumericUpDowns[i].Enabled = true;
}
smallest = i;
break;
}
// find the largest and enable its min:
var largest = -1;
for (var i = _checkBoxs.Length - 1; i >= 0; i--)
{
if (!_checkBoxs[i].Checked) continue;
if (_minimumsNumericUpDowns[i] != null)
{
_minimumsNumericUpDowns[i].Enabled = true;
}
largest = i;
break;
}
// enable both for everything between smallest and largest:
var tempVar = largest - 1;
for (var i = (smallest + 1); i <= tempVar; i++)
{
if (!_checkBoxs[i].Checked) continue;
if (_minimumsNumericUpDowns[i] != null)
{
_minimumsNumericUpDowns[i].Enabled = true;
}
if (_maximumsNumericUpDowns[i] != null)
{
_maximumsNumericUpDowns[i].Enabled = true;
}
}
}
So I can check each state as required:
I want to check if Extra Light is check:
// Extra Light
if (!cbXLight.Checked) return;
if (nXLightMax.Enabled == false)
{
_structCategoryType = XLight;
CheckStructureSheets();
}
else
{
if (nXLightMax.Value > 0)
{
_dMax = nXLightMax.Value;
_structCategoryType = XLight;
CheckStructureSheets();
}
else
{
MessageBox.Show(#"Extra Light Max cannot be zero (0)");
}
}
and next light checks both:
// Light
if (cbLight.Checked)
{
if (nLightMin.Enabled == false && nLightMax.Enabled == false)
{
_structCategoryType = Light;
CheckStructureSheets();
}
else
{
if (nLightMin.Enabled && nLightMin.Value > 0)
{
if (nXLightMax.Enabled && nLightMin.Enabled && nLightMax.Enabled == false)
{
_dMin = nLightMin.Value;
_structCategoryType = Light;
CheckStructureSheets();
}
else
{
if (nLightMax.Value > 0)
{
_dMin = nLightMin.Value;
_dMax = nLightMax.Value;
_structCategoryType = Light;
CheckStructureSheets();
}
else
{
MessageBox.Show(#"Light Max cannot be zero (0)");
return;
}
}
}
else if (nLightMin.Enabled == false && nLightMax.Enabled)
{
if (nLightMax.Value > 0)
{
_dMax = nLightMax.Value;
_structCategoryType = Light;
CheckStructureSheets();
}
else
{
MessageBox.Show(#"Light Max cannot be zero (0)");
}
}
else
{
MessageBox.Show(#"Light Min cannot be zero (0)");
return;
}
}
}
Hope this helps someone.
Tim
thanks for #AlexJoliq and #BrettCaswell. just want to inform that before Alex edited his answer from using "==" to "!=", i (thought) already solved the problem. but i don't know where is the more effective and efficient way, alex's or mine.
below is my code for DisableIfValueIsTrue():
if (add1 + add2 == sum.Value) sum.Enabled = false;
if (add1 - add2 == difference.Value) difference.Enabled = false;
if (add1 * add2 == product.Value) product.Enabled = false;
if (add1 / add2 == quotient.Value) quotient.Enabled = false;
I am trying to use mod division to determine whether a year in a loop is a census or election year, and I have two issues:
1. I cannot get the wording in line with the year for ex:
It is like:
2000
this is an election year
this is a census year
2001
but I need it to say:
2000, this is an election year, this is a census year
2001 etc
2 : My math is some sort of wrong but I am having trouble identifying why or where, the division needs to apply to a user entered year range, and it needs to divide each year by 10, or 4, and the years that have no remainder are election or census years, but it is not doing that properly, it is not dividing all of the years, just some. My code is this:
private void buttonGo_Click(object sender, EventArgs e)
{
//Variables
int startYr = 0;
int endYr = 0;
int yearDisp = 0;
//Input Validation
startYr = int.Parse(textBoxStartYr.Text);
endYr = int.Parse(textBoxEndYr.Text);
if (int.TryParse(textBoxStartYr.Text, out startYr))
{
//correct
}
else
{
MessageBox.Show("Please enter a four digit year");
return;
}
if (int.TryParse(textBoxEndYr.Text, out endYr))
{
//correct
}
else
{
MessageBox.Show("Please enter a four digit year");
return;
}
//Loop
for (yearDisp = startYr; yearDisp <= endYr; yearDisp++)
{
listBoxDisp.Items.Add("Year:" + yearDisp.ToString());
if (checkBoxCensus.Checked == true )
{
if ((yearDisp % 10) == 0)
{
listBoxDisp.Items.Add("This is a census year");
}
else { }
}
else
{
//nothing needed
}
if (checkBoxElection.Checked == true)
{
if ((yearDisp % 4) == 0)
{
listBoxDisp.Items.Add("This is an election year");
}
else { }
}
else
{
//nothing
}
}
}
Try this:
private void buttonGo_Click(object sender, EventArgs e)
{
// Variables
int startYr = 0;
int endYr = 0;
bool checkForCensus = checkBoxCensus.Checked;
bool checkForElection = checkBoxElection.Checked;
// Input Validation
string errorMsg = "";
if (!int.TryParse(textBoxStartYr.Text, out startYr))
errorMsg += "Please enter a four digit year";
if (!int.TryParse(textBoxEndYr.Text, out endYr))\
errorMsg += String.Format("{0}Please enter a four digit year",
errorMsg == "" ? "" : " ");
if (errorMsg != "")
{
MessageBox.Show(errorMsg);
return;
}
// Loop
for (int yearDisp = startYr; yearDisp <= endYr; yearDisp++)
{
bool isCensusYear, isElectionYear;
if (checkForCensus && (yearDisp % 10) == 0)
isCensusYear = true;
if (checkForElection && (yearDisp % 4) == 0)
isElectionYear = true;
listBoxDisp.Items.Add(String.Format("{0}: {1}{2}{3}",
yearDisp.ToString(),
isCensusYear ? "this is a census year" : "",
(isCensusYear && isElectionYear) ? "," : "",
isElectionYear ? "this is an election year" : ""
));
}
}
Notes:
The empty if and else statements are unnecessary. I have removed the to make them more concise.
On the topic of conditionals in if statements: the ! means "not" or "the opposite of". Examples: !false == true and !true == false.
You do not need the initial int.Parse() statements because TryParse()'s second parameter is an out parameter (it outputs the parsed integer).
I created two variables which get the value of the check box. That way you don't have to check the value every time the loop is executed.
I used a ternary operator and String.Format() to determine what text to display.
Although you didn't mention it, I did change the input validation so that only one message box is displayed.
Try this for your listbox issue.
for (yearDisp = startYr; yearDisp <= endYr; yearDisp++)
{
int index = listBoxDisp.Items.Add("Year:" + yearDisp.ToString());
if (checkBoxCensus.Checked == true)
{
if ((yearDisp % 10) == 0)
{
listBoxDisp.Items[index] += ",This is a census year";
}
else { }
}
else
{
//nothing needed
}
if (checkBoxElection.Checked == true)
{
if ((yearDisp % 4) == 0)
{
listBoxDisp.Items[index] += ",This is an election year";
}
else { }
}
else
{
//nothing
}
}
Try something like this:
private void buttonGo_Click(object sender, EventArgs e)
{
//Variables
int startYr = 0;
int endYr = 0;
int yearDisp = 0;
//Input Validation
if (!int.TryParse(textBoxStartYr.Text, out startYr))
{
MessageBox.Show("Please enter a four digit year");
return;
}
if (!int.TryParse(textBoxEndYr.Text, out endYr))
{
MessageBox.Show("Please enter a four digit year");
return;
}
//Loop
for (yearDisp = startYr; yearDisp <= endYr; yearDisp++)
{
bool isElection = 0 == (yearDisp % 4);
bool isCensus = 0 == (yearDisp % 10);
if (isCensus && checkBoxCensus.Checked && isElection && checkBoxElection.Checked)
{
listBoxDisp.Items.Add(String.Format("{0} This is a both a census year and an election year", yearDisp));
}
else if (isCensus && checkBoxCensus.Checked)
{
listBoxDisp.Items.Add(String.Format("{0} This is a census year", yearDisp));
}
else if (isElection && checkBoxElection.Checked)
{
listBoxDisp.Items.Add(String.Format("{0} This is an election year", yearDisp));
}
else {
listBoxDisp.Items.Add(yearDisp.ToString());
}
}
}
Here's a more concise version of the for loop:
for (yearDisp = startYr; yearDisp <= endYr; yearDisp++)
{
bool isElection = (0 == (yearDisp % 4)) && checkBoxCensus.Checked;
bool isCensus = 0 == (yearDisp % 10) && checkBoxElection.Checked;
string text = yearDisp.ToString();
if (isCensus && isElection)
{
text += " This is a both a census year and an election year";
}
else if (isCensus)
{
text += " This is a census year", yearDisp;
}
else if (isElection)
{
text += " This is an election year";
}
listBoxDisp.Items.Add(text);
}