I have to validate some inputs the user makes, and send a error message
this is what I got so far
// probes the methods to check for validity.
private void btnCalculate_Click(object sender, EventArgs e)
{
if (!(ValidWidth(float.Parse(txtWidth.Text))))
{
return;
}
if (!(ValidLength(float.Parse(txtLength.Text))))
{
return;
}
if (!(ValidDepth(float.Parse(txtAvgDepth.Text))))
{
return;
}
}
My problem is when I enter the values into Length, Width, and Depth. It only does it in order..what I mean is if I don't enter a width and leave it blank and put in length and depth it gives me a unhandled expection.
here are my methods
/** Created a boolean method to test if the written width is valid OR not valid **/
private bool ValidWidth(float Width1) {
float Width = float.Parse(txtWidth.Text);
{
if (Width >= 2 & Width <= 20)
{
return true;
}
else
{
string Title = "Data Invalid";
string Msg = "Width Measurement is invalid \n Place enter a value between 2 and 20";
DialogResult Response;
Response = MessageBox.Show(Msg, Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return false;
}
}
}
/** Created a boolean method to test if the written legnth is valid OR not valid **/
private bool ValidLength(float Length1)
{
float Length = float.Parse(txtLength.Text);
{
if (Length >= 5 & Length <= 50)
{
return true;
}
else
{
string Title = "Data Invalid";
string Msg = "Legnth Measurement is invalid \n Place enter a value between 5 and 50";
DialogResult Response;
Response = MessageBox.Show(Msg, Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return false;
}
}
}
/** Created a boolean method to test if the written legnth is valid OR not valid **/
private bool ValidDepth(float Depth1)
{
float Depth = float.Parse(txtAvgDepth.Text);
if (Depth >= 2 & Depth <= 4)
{
return true;
}
else
{
string Title = "Data Invalid";
string Msg = "Average Depth Measurement is invalid \n Place enter a value between 2 and 4";
DialogResult Response;
Response = MessageBox.Show(Msg, Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return false;
}
}
The Parse method will throw an exception if you feed it an empty string. You should catch that exception, or use TryParse.
You messed up every thing in your code. first there is a method float.TryParse which attempts to convert your string into float number. but it will not throw an exception if conversion failed. instead it gives a boolean value which tells parse succeeded or not.
I think this is better.
private void btnCalculate_Click(object sender, EventArgs e)
{
if(!ValidateWidth(txtWidth.Text) ||
!ValidateLength(txtLength.Text) ||
!ValidateDepth(txtAvgDepth.Text)) // if any of these failed
{
MessageBox.Show(Msg, Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
I write ValidateWidth for you as an example.
private string Title = "Data Invalid";
private string Msg;
private bool ValidateWidth(string input)
{
float width;
if(float.TryParse(input, out width))
{
if (Width >= 2 && Width <= 20)
{
return true;
}
}
Msg = "Width Measurement is invalid \n Place enter a value between 2 and 20";
return false;
}
Related
I am trying to save the .text of a label to a database but sometimes that label is an infinity symbol. To catch for this I have created an if statement which checks if the label is a number or not and throws a message box up to tell the user. However more often than not the label will be a decimal number and the if statement throws up the message box. I was wondering if anyone could help me out please?
private void btnSaveResults_Click(object sender, EventArgs e)
{
btnClearData.Enabled = true;
if (System.Text.RegularExpressions.Regex.IsMatch(lblAerobicCap.Text, "[^0-9]"))
{
MessageBox.Show("Im sorry, there seems to have been an error in the inputting of the readings, please restart the test");
}
else
{
AthletesDetailsNew users = new AthletesDetailsNew();
DateTime dateTimeVariable = DateTime.Now;
users.Date_Of_Test = dateTimeVariable;
users.First_Name = comboBoxFirstName.Text;
users.Surname = comboBoxNewSurname.Text;
users.Age = int.Parse(comboBoxAge.Text);
users.Account_Number = int.Parse(comboBoxAccountNumber.Text);
users.Aerobic_Capacity = /*Math.Truncate*/(decimal.Parse(lblAerobicCap.Text));
DataClassDataContext dbCtx = new DataClassDataContext();
dbCtx.AthletesDetailsNews.InsertOnSubmit(users);
try
{
dbCtx.SubmitChanges();
MessageBox.Show("Data saved");
}
catch
{
MessageBox.Show("Data failed to save");
}
}
}
You should use the .TryParse() method for this.
for example:
decimal value;
bool isNumber = Decimal.TryParse(inputVariable, out value);
Use decimal.TryParse so in case of success you can reuse the result
decimal aerobicCap = -1;
if (!decimal.TryParse( lblAerobicCap.Text, out aerobicCap))
{
MessageBox.Show("Im sorry, there seems to have been an error in the inputting of the readings, please restart the test");
}
else
{
// code ...
users.Aerobic_Capacity = aerobicCap;
I think you need to trim the spaces from lblAerobicCap.Text prior to checking if the value is a number. Something like lblAerobicCap.Text = lblAerobicCap.Text.Trim().
lblAerobicCap.Text = lblAerobicCap.Text.Trim();
if (System.Text.RegularExpressions.Regex.IsMatch(lblAerobicCap.Text, "[^0-9]"))
{
MessageBox.Show("Im sorry, there seems to have been an error in the inputting of the readings, please restart the test");
}
[ ... ]
Better still avoid users entering anything but numbers. That way you do not have to validate the input.
For the digits use something like this:
void Control_KeyPress(object sender, KeyPressEventArgs e)
{
if (!Char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
}
Decimal:
void Control_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode != Keys.Decimal)
{
e.Handled = true;
}
}
I have used an extension method in the past which works nicely for me:
public static bool IsNumber(this object value)
{
return value is sbyte
|| value is byte
|| value is short
|| value is ushort
|| value is int
|| value is uint
|| value is long
|| value is ulong
|| value is float
|| value is double
|| value is decimal;
}
object testObject = 0.1;
if (testObject.IsNumber()) { MessageBox.Show("Hooray!"); }
So, this program functions as it should, but I don't think the code is very "clean," so I'm looking for suggestion. Two of the big issues I have:
For the method public double temperatureInFahrenheit, I want to pass the argument celsiusTemperature to the function instead of having to redeclare the variable, convert it from the text to the double, etc. Whenever I attempt to try that I get an error in the MessageBox.Show when I try to call the function myAirport.temperatureInFahrenheit (I don't specifically remember what the error is, so I'll have to recode if that's needed). Any thoughts on what I can do to make this work?
The MessageBox.Show in the public partial class Form1 seems like messy code to me. What I'd like to do is write a method in internal class Airport, where the necessary arguments are passed to the method, and then just do something like MessageBox.Show(myAirport.message()), but I'm assuming if I tried that I'd get the same error as I'm getting for 1. Any thoughts?
Again, the code is completely functional and works and meets the required specifications, but I don't like just having functional code, I like having functional code that's "pretty." Note: I don't have comments for any of the methods, variables, etc. I'm putting those in right now, but thought I'd try and get some feedback first.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string airportName;
double celsiusTemperature, elevation;
if (String.IsNullOrEmpty(txtAirport.Text)) {
MessageBox.Show("You did not enter a name for the airport. Please enter a name for the airport.");
return;
} else
{
airportName = Convert.ToString(txtAirport.Text);
}
if (Double.TryParse(txtTemperature.Text, out celsiusTemperature))
{
if (celsiusTemperature > 50 || celsiusTemperature < -50)
{
MessageBox.Show("The value you entered for temperature is outside the acceptable range. Please reenter the information");
Application.Restart();
}
}
else
{
MessageBox.Show("You did not enter a numeric value for the temperature. Please enter a valid, i.e. numeric, value for the temperature.");
return;
}
if (Double.TryParse(txtElevation.Text, out elevation))
{
if (elevation > 12000 || elevation < -300)
{
MessageBox.Show("The value you entered for elevation is outside the acceptable range. Please reenter the information.");
Application.Restart();
}
}
else
{
MessageBox.Show("You did not enter a numeric value for the elevation. Please enter a valid, i.e. numeric, value for the elevation.");
return;
}
Airport myAirport = new Airport(airportName, celsiusTemperature, elevation);
MessageBox.Show("The airport name is: " + myAirport.airportName(airportName) + Environment.NewLine + "The Celsius temperature is: " + myAirport.celsiusTemperature(celsiusTemperature)
+ Environment.NewLine + "The Fahrenheit temperature is: " + myAirport.temperatureInFahrenheit(celsiusTemperature) + Environment.NewLine + "The elevation is: " + myAirport.elevation(elevation));
}
private void button2_Click(object sender, EventArgs e)
{
Close();
}
}
internal class Airport
{
private string airportName1;
private double celsiusTemperature1;
private double elevation1;
public Airport(string airportName1, double celsiusTemperature1, double elevation1)
{
this.airportName1 = airportName1;
this.celsiusTemperature1 = celsiusTemperature1;
this.elevation1 = elevation1;
}
public string airportName(string airportName1)
{
return airportName1;
}
public double celsiusTemperature(double celsiusTemperature1)
{
return celsiusTemperature1;
}
public double elevation(double elevation1)
{
return elevation1;
}
public double temperatureInFahrenheit(double celsiusTemperature1)
{
double fahrenheitTemperature = 0;
fahrenheitTemperature = celsiusTemperature1 * (1.8) + 32;
return fahrenheitTemperature;
}
}
}
Here is an example of how you could simplify the Airport class:
public class Program
{
static void Main(string[] args)
{
var airport = new Airport { AirportName = "JFK", Temperature = 28.5 };
Console.WriteLine(airport.ToString());
}
}
public class Airport
{
private string _airportName;
private double _temperatureInCelsius;
private double _temperatureInFahrenheit;
public string AirportName
{
get
{
return _airportName;
}
set
{
if (string.IsNullOrWhiteSpace(value))
{
throw new Exception("You did not enter a name for the airport. Please reenter the information.");
}
_airportName = value;
}
}
public double Temperature
{
get
{
return _temperatureInCelsius;
}
set
{
if (value > 50 || value < -50)
{
throw new Exception("The value you entered for temperature is outside the acceptable range. Please reenter the information");
}
_temperatureInCelsius = value;
_temperatureInFahrenheit = _temperatureInCelsius *(1.8) + 32;
}
}
public override string ToString()
{
return string.Format(
"The airport name is: {0}\r\nThe Celsius temperature is: {1}\r\nThe Fahrenheit temperature is: {2}", _airportName, _temperatureInCelsius, _temperatureInFahrenheit);
}
}
Notice that the AirportName setter validates the passed airport name (via value) and if it's not valid, then an exception is thrown.
I will leave the other property - elevation, as an excercise for you to finish.
Regards the Message.Show you can do this:
Message.Show(airport.ToString());
The ToString() method return a string that describes the airport.
My code is a suggestion, you don't have to use it exactly (i.e. you might not like throwing an exception from the setters. Instead you could validate the values before creating an Airport instance.), but hopefully it will guide you.
There are many ways to separate the different requirements, so i try to give the idea.
First, a simple airport data class with properties and inside validation (That means invalid instances are possible):
internal class Airport
{
private string _airportName;
private double _celsiusTemperature;
private double _elevation;
public Airport(string airportName, double celsiusTemperature, double elevation)
{
this._airportName = airportName;
this._celsiusTemperature = celsiusTemperature;
this._elevation = elevation;
}
public string AirportName
{
get
{
return _airportName;
}
set
{
_airportName = value;
}
}
public double CelsiusTemperature
{
get
{
return _celsiusTemperature;
}
set
{
_celsiusTemperature = value;
}
}
public double Elevation
{
get
{
return _elevation;
}
set
{
_elevation = value;
}
}
public double TemperatureInFahrenheit
{
get
{
return _celsiusTemperature * (1.8) + 32.0;
}
set
{
if (value != 32.0)
{
_celsiusTemperature = (value - 32.0) / (1.8);
}
else
{
_celsiusTemperature = 0.0;
}
}
}
public bool IsValid(out string errorMessage)
{
bool result = false;
bool ok = true;
errorMessage = "";
if (String.IsNullOrEmpty(_airportName))
{
ok = false;
errorMessage = "You did not enter a name for the airport.";
}
if (_celsiusTemperature > 50 || _celsiusTemperature < -50)
{
ok = false;
errorMessage = "The value you entered for temperature is outside the acceptable range.";
}
if (_elevation > 12000 || _elevation < -300)
{
ok = false;
errorMessage = "The value you entered for elevation is outside the acceptable range.";
}
result = ok;
return result;
}
}
Note that Fahrenheit is a calculated value based on Celsius. It could be vice versa.
Also note the validation. The airport class is accepting all values, only the type of the fields is defined. It does the semantic check (business logic).
Now, how to use it:
private void button1_Click(object sender, EventArgs e)
{
string airportName;
double celsiusTemperature;
double elevation;
// Get data from controls and do syntactic checks
bool ok = true;
airportName = txtAirport.Text;
ok = Double.TryParse(txtTemperature.Text, out celsiusTemperature);
if (!ok)
{
// Error
MessageBox.Show("The value you entered for temperature is not a number!", "Error");
}
ok = Double.TryParse(txtElevation.Text, out elevation);
if (!ok)
{
// Error
MessageBox.Show("The value you entered for elevation is not a number!", "Error");
}
if (ok)
{
// Create the instance of the data class and do semantic checks
Airport myAirport = new Airport(airportName, celsiusTemperature, elevation);
string errorMessage;
if (!myAirport.IsValid(out errorMessage))
{
// Error
MessageBox.Show(errorMessage + " Please reenter the information", "Error");
}
else
{
// Ok, data is valid. Continue normal work...
MessageBox.Show("The airport name is: " + myAirport.AirportName + Environment.NewLine +
"The Celsius temperature is: " + myAirport.CelsiusTemperature + Environment.NewLine +
"The Fahrenheit temperature is: " + myAirport.TemperatureInFahrenheit + Environment.NewLine +
"The elevation is: " + myAirport.Elevation);
}
}
You get the data from controls and do syntactic checks. If everthing is allright, you let the class do the semantic checks itself. Here it will give a string as message details, but many otehr ways are passible.
So, in the end, if a syntatic error occurs, the user gets a message and can continue. If a semantic error occurs, the user gets a message and can continue. If everything is ok, you can operate an valid data.
Hope this helps...
I think, you should refactor your code in the following ways:
Airport seems to be a data class. So it should not know about the TextBox's of Form1. So, try to separate them.
For easy access, you should think of properties (or getter/setter methods) for your fields in the airport class.
You are checking the data when you are reading it out of the airport class. What if you are never reading it or using it inside before? So, you should separate this.
If you estimate an error, you are restarting the complete application. That is normaly not a good deal to the user. So try to show the error and let the user do some corrections. And check again, and so on...
If Airport is data class, then you can have to properties for Celsius and Fahrenheit. No matter what representation you have internaly.
I would like to give these hints without code first, so you can think and try for yourself before looking at a complete solution. Then, if you get stuck somewhere, i (and others) will give more concrete tips.
So, good luck for you...
I am relatively new at this and have been racking my brain attempting to get my program to work properly and it just won't. I am working in Visual Studio 2012 C# on a Forms Application.
I need it to produce a distinct error message when the user input value is more than 0 but less than 10,000. It also must produce a distinct error message when the user enters a non-numeric value and a distinct error message when the user fails to enter any value at all.
The code I've written so far produces a distinct error message when the user enters a non-numeric value or when they fail to enter any value at all, but it does not trigger an error message when the user enters a value that is below or over the required range.
It is as if the compiler is ignoring the code I've written for the first exception/overflow exception and only recognizing the code for the second and final exception. My code has no coding errors. It appears that my problem is in the logic.
Please help me if you can. My code is below thanks!
private void btnCalculate_Click(object sender, System.EventArgs e)
{
try
{
{
decimal subtotal = Convert.ToDecimal(txtSubtotal.Text);
decimal discountPercent = .25m;
decimal discountAmount = subtotal * discountPercent;
decimal invoiceTotal = subtotal - discountAmount;
lblDiscountPercent.Text = discountPercent.ToString("p1");
lblDiscountAmount.Text = discountAmount.ToString("c");
lblTotal.Text = invoiceTotal.ToString("c");
}
}
catch (OverflowException)
{
decimal subtotal = Convert.ToDecimal(txtSubtotal.Text);
if (subtotal <= 0)
{
MessageBox.Show("Subtotal must be greater than $0.00. ", "Error Entry");
txtSubtotal.Focus();
}
if (subtotal >= 10000)
{
MessageBox.Show("Subtotal must be less than $10000.00. ", "Error Entry");
txtSubtotal.Focus();
}
}
catch (Exception)
{
if (txtSubtotal.Text == "")
{
MessageBox.Show("Subtotal is a required field. ", "Error Entry");
}
else
{
MessageBox.Show(
"Please enter a valid Number for the subtotal field.", "Error Entry");
txtSubtotal.Focus();
}
}
}
private void btnExit_Click(object sender, System.EventArgs e)
{
this.Close();
}
private void txtSubtotal_TextChanged(object sender, EventArgs e)
{
}
}
}
I would used KeyEvent press enter or Leave event for this, first I need to create generic class for verification if the input from the user is not a string.
Condition:
1 verify if the input is not a string Im using generic for general purposes class.
public class iCnF()
{
public static System.Boolean IsNumeric(System.Object Expression)
{
if (Expression == null || Expression is DateTime)
return false;
if (Expression is Int16 || Expression is Int32 || Expression is Int64 || Expression is Decimal || Expression is Single || Expression is Double || Expression is Boolean)
return true;
try
{
if(Expression is string)
Double.Parse(Expression as string);
else
Double.Parse(Expression.ToString());
return true;
} catch {} // just dismiss errors but return false
return false;
}
}
Then I need to verify if the input is not empty
private void txtSubtotal_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Tab)
{
if (txtSubtotal.Text.Length > 0)
{
bool sd = iCnF.IsNumeric(txtSubtotal.Text);
if (sd == false)
{
MessageBox.Show("Subtotal must be a numeric value. ", "Error Entry");
txtSubtotal.Clear();
txtSubtotal.Focus();
}
else
{
decimal subtotal = Convert.ToDecimal(txtSubtotal.Text);
if (subtotal <= 0)
{
MessageBox.Show("Subtotal must be greater than $0.00. ", "Error Entry");
txtSubtotal.Focus();
}
if (subtotal >= 10000)
{
MessageBox.Show("Subtotal must be less than $10000.00. ", "Error Entry");
txtSubtotal.Focus();
}
}
}
else
{
MessageBox.Show("Subtotal must not be empty. ", "Error Entry");
txtSubtotal.Focus();
}
}
}
if not empty and numberic value my subtotal <= 0 and subtotal >= 10000
Hope this will help you :D
As I already mentioned in comment you should consider moving your code out of catch block.
In this case you should think of creating a simple method which will validate your input and produces output message.
An example is for you:
private bool IsPageValid()
{
string errorMessage = string.Empty;
bool isValid = true;
if (subtotal <= 0)
{
errorMessage+="<li>"+"<b>Subtotal must be greater than $0.00. ", "Error Entry"+ "</b><br/>";
txtSubtotal.Focus();
isValid=false;
}
}
Likewise write other clause of validations in this function..This will validate each of your condition and if fails it would make the isValid false thus not allowing users to submit.
Now you should call this function in your button click.
protected void btnSubmit_Click(object sender, EventArgs e)
{
ClearMessage();
if (IsPageValid().Equals(true))
{
// allow next action to happen.
}
}
Code should look like this
try {
decimal subtotal = Convert.ToDecimal(txtSubtotal.Text);
try {
if(x<0 || x>10000){
throw new OverFlowException("");
}
//Do what ever you want
}
catch(Exception ex){
// catch overflow
}
}
catch(Exception ex){
// catch nonnumeric value
}
I have made a form which works perfectly fine when the fields are filled in. If you click the "convert" button with a blank textbox, it throws an error due to parsing a null value.
Obviously this means that I've declared my variable upon the button click.
I would also like a message box to pop up if the field is empty, to prompt the user to enter data.
Here is the code I have for the convert button:
private void exitButton_Click(object sender, EventArgs e)
{
//closes the form
this.Close();
}
private void convertButton_Click(object sender, EventArgs e)
{
decimal measurementDecimal = decimal.Parse(enterTextBox.Text);
//if else arguments for radio buttons
if (string.IsNullOrWhiteSpace(enterTextBox.Text))
{
MessageBox.Show("Please enter a value");
}
else if (inchesFromRadioButton.Checked && (inchesToRadioButton.Checked))
{
convertedTextBox.Text = measurementDecimal.ToString();
}
else if (inchesFromRadioButton.Checked && (feetToRadioButton.Checked))
{
convertedTextBox.Text = (measurementDecimal / 12).ToString();
}
else if (inchesFromRadioButton.Checked && (yardsToRadioButton.Checked))
{
convertedTextBox.Text = (measurementDecimal / 36).ToString();
}
else if (feetFromRadioButton.Checked && (inchesToRadioButton.Checked))
{
convertedTextBox.Text = (measurementDecimal * 12).ToString();
}
else if (feetFromRadioButton.Checked && (feetToRadioButton.Checked))
{
convertedTextBox.Text = measurementDecimal.ToString();
}
else if (feetFromRadioButton.Checked && (yardsToRadioButton.Checked))
{
convertedTextBox.Text = (measurementDecimal / 3).ToString();
}
else if (yardsFromRadioButton.Checked && (inchesToRadioButton.Checked))
{
convertedTextBox.Text = (measurementDecimal * 36).ToString();
}
else if (yardsFromRadioButton.Checked && (feetToRadioButton.Checked))
{
convertedTextBox.Text = (measurementDecimal * 3).ToString();
}
else if (yardsFromRadioButton.Checked && (yardsToRadioButton.Checked))
{
convertedTextBox.Text = measurementDecimal.ToString();
}
else
{
MessageBox.Show("Parameters not set. Please select a 'From' and 'To'");
}
Solution 1 : You can perform null or empty check before parsing the input value.and if it is invalid display warning and return from the method.
Try This:
private void convertButton_Click(object sender, EventArgs e)
{
//if else arguments for radio buttons
if (string.IsNullOrWhiteSpace(enterTextBox.Text))
{
MessageBox.Show("Please enter a value");
return;
}
/*Your remaining code here*/
decimal measurementDecimal = decimal.Parse(enterTextBox.Text);
Solution 2: You can use decimal.TryParse() method for checking the valid decimal value.
From MSDN:
Converts the string representation of a number to its Decimal
equivalent. A return value indicates whether the conversion succeeded
or failed.
private void convertButton_Click(object sender, EventArgs e)
{
decimal measurementDecimal ;
if (!decimal.TryParse(enterTextBox.Text,out measurementDecimal))
{
MessageBox.Show("Please enter a valid value");
return;
}
else
{
/*Your remaining code here*/
}
I am having trouble validating user input, I have the following loop which definitely catches it but when the loop starts again the user doesn't have a chance to enter a different value so the value is the same and just creates an endless loop.
private void guess_Click(object sender, EventArgs e)
{
int guessInt = 0;
bool pass = false;
int number;
while (pass == false)
{
if (guessInput.Text != "")
{
pass = Int32.TryParse(guessInput.Text, out number);
if (pass)
{
guessInt = number;
}
else
{
MessageBox.Show("You did not enter an integer, please enter a integer", "Invalid Values", MessageBoxButtons.OK, MessageBoxIcon.Error);
guessInput.Text = "";
}
}
else MessageBox.Show("You did not enter anything, please enter a integer", "Invalid Values", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
guess.Enabled = false;
next_Guess.Enabled = true;
if (guessInt == randomArray[x])
{
result.Text = ("You Win! The correct number was " + randomArray[x]);
right += 1;
correctAnswers.Text = right.ToString();
}
else
{
result.Text = ("Sorry you lose, the number is " + randomArray[x]);
wrong += 1;
incorrectAnswers.Text = wrong.ToString();
}
hintLabel.Enabled = false;
x++;
}
So how can the user have a chance to reenter a value and the loop start again or should I be using a try/catch attempt here?
int number;
if(string.IsNullOrEmpty(guessInput.Text))
{
MessageBox.Show("You did not enter an integer, please enter a integer", "Invalid Values", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if(Int32.TryParse(guessInput.Text, out number))
{
guessInt = number;
}else
{
MessageBox.Show("You did not enter an integer, please enter a integer", "Invalid Values", MessageBoxButtons.OK, MessageBoxIcon.Error);
guessInput.Text = "";
return;
}
// when come to here you have guessInt, process it
guess.Enabled = false;
next_Guess.Enabled = true;
if (guessInt == randomArray[x])
{
result.Text = ("You Win! The correct number was " + randomArray[x]);
right += 1;
correctAnswers.Text = right.ToString();
}
else
{
result.Text = ("Sorry you lose, the number is " + randomArray[x]);
wrong += 1;
incorrectAnswers.Text = wrong.ToString();
}
hintLabel.Enabled = false;
x++;
It seems you don't need a while there:
int number;
if(guessInput.Text != "")
{
var pass = Int32.TryParse(guessInput.Text, out number);
if (pass)
{
guessInt = number;
}
else
{
MessageBox.Show("You did not enter an integer, please enter a integer", "Invalid Values", MessageBoxButtons.OK, MessageBoxIcon.Error);
guessInput.Text = "";
}
}
if you want to validate also for empty values, just remove the first if:
int number;
var pass = Int32.TryParse(guessInput.Text, out number);
if (pass)
{
guessInt = number;
}
else {
MessageBox.Show("You did not enter an integer, please enter a integer", "Invalid Values", MessageBoxButtons.OK, MessageBoxIcon.Error);
guessInput.Text = "";
}
As soon as the user clicks OK on the messagebox, the loop is going to run again without giving the user a chance to change the value.
What you need to do is run validation only when they enter a guess. That is, rather than have a loop, have some code that is triggered by an event (such as clicking a button) or by the validation callback provided by winforms.
Here's an example and short article I found on using the validation callback:
http://blog.scosby.com/post/2010/02/11/Validation-in-Windows-Forms.aspx
In that example, see:
private void buttonSave_Click - this is where you would put your messagebox, and
private void textBoxNumber_Validating - this is where you would put your pass = Int32.TryParse(guessInput.Text, out number)... code.