.net v3.5 readline errors when user submits null or string
I am writing a console application, that gives the user a numerical choice to pick from (1-3). I have my logic down correctly, so that if they select 1-3 it works, but will cycle back through the loop if they choose any number outside that range and write a string error message "Invalid Entry! Please select 1-3 only.".
The problem I am running into is that if you just hit enter, without entering anything at all, it errors out. Or if you submit an alpha character instead of a number, it also errors out. How do I write it so that null entries or string/char entries will not bug it out when it is looking for only an int entry?
Thanks in advance for any help.
Re: .net v3.5 readline errors when user submits null or string
In your submit, I'd do a check with the following:
Code:
if (String.IsNullOrWhiteSpace(txtValue.Text))
{
// Display MessageBox -- indicating null
}
else
{
// Perform non-null checks and valid code
}
Re: .net v3.5 readline errors when user submits null or string
You're using the wrong control for the job. You should be using a NumericUpDown that has a range of 1-3. Now your users cannot enter invalid input, period.
The error checking code above will not get you there in it's own. It's always better to simply not allow invalid input from the get go rather than popping up an error after the fact.
Re: .net v3.5 readline errors when user submits null or string
I don't think you have the luxury of text boxes nor up down controls in a console app.
What you need to do is use a try catch block or a try parse and give a message when it fails to parse a number from the entry.
Re: .net v3.5 readline errors when user submits null or string
I'm sorry; I completely missed the Console App part in the first sentence...
DataMiser is right; in this case, simply use int.TryParse first. if it fails, show an error. If it succeeds, make sure that it is in the valid range.
Re: .net v3.5 readline errors when user submits null or string
Thanks a lot for the response guys, I ended up finding my answer in TryParse:
here's the before code:
Console.WriteLine("Please choose a character Race: \n1)Human \n2)Elf \n3)Orc");
race = int.Parse(Console.ReadLine());
after code:
Console.WriteLine("Please choose a character Race: \n1)Human \n2)Elf \n3)Orc");
int.TryParse(Console.ReadLine(), out race);