I'm working on a project in Visual Studios 2015 (Visual c#).
I have a textbox in which is introduced a number beetween 0 and 11.So if the number isn't beetween 0 and 11 or in the textbox1 is introduced a char or string value, a Message Box will pop up saying that the value introduced it's incorrect.
But , if I delete the numbers from the textbox1 or introduce a char character ,press space - the application chrases.
Here is the code :
private void textBox1_TextChanged(object sender, EventArgs e)
{
int a;
a = Convert.ToInt32(textBox1.Text);
if (textBox1.Text == null)
{
MessageBox.Show("incorrect");
}
else
if (a < 0 || a > 11)
{
MessageBox.Show("incorrect");
}
}
I need to find a method that doesn't crashes when I introduce a char or string value ,or a number that isn't between 0 and 11.
(the numbers introduced in the textbox1 are always int)
Your app crashes because you are trying to convert TextBox.Text value to int and it is possible that this value cannot be converted to int so, you get exception. If this value is non-number or empty string then Convert.ToInt32() crashes (throws exception and this exception in not handled - crash).
In your case it will be better to use int.TryParse() method instead of Convert.ToInt32() - if int.TryParse() returns true then it is number and you can check if value is in needed range, if int.TryParse() returns false then value cannot be parsed to int(it is some non-digit string):
private void textBox1_TextChanged(object sender, EventArgs e)
{
int a;
bool parsed = int.TryParse(textBox1.Text, out a);
if (!parsed || a < 0 || a > 11)
{
MessageBox.Show("incorrect");
}
}
Try This
private void textBox1_TextChanged(object sender, EventArgs e)
{
int a;
int = 0;
try
{
a = Convert.ToInt32(textBox1.Text);
}
catch(Exception exc){
MessageBox.Show("incorrect exception thrown");
}
if (textBox1.Text == null)
{
MessageBox.Show("incorrect");
}
else
if (a < 0 || a > 11)
{
MessageBox.Show("incorrect");
}
}
The try parse equivelant:
private void textBox1_TextChanged(object sender, EventArgs e)
{
int a;
bool succes = int.TryParse(textBox1.Text, out a);
if(!succes)
{
MessageBox.Show("incorrect");
return;
}
if (a < 0 || a > 11)
{
MessageBox.Show("incorrect");
}
// ... Do stuff to a?
}
Your conversion is not correct
private void textBox1_TextChanged(object sender, EventArgs e)
{
int a;
bool result= int.TryParse(textBox1.Text, out a);
if (textBox1.Text == null || res)
{
MessageBox.Show("incorrect");
}
else
if (a < 0 || a > 11)
{
MessageBox.Show("incorrect");
}
}
Related
My application should get user input as well as a number of repetitions.
After it's verified as positive data, it should display results in a list box.
Results should be phrase # of reps entered.
I know I need to use a while loop but where am I going wrong. Below is what I have so far:
private void btnDisplay_Click(object sender, EventArgs e)
{
// Delcare variables
int Numberofreps;
int Count = 1;
string Phrase = txtPhrase.Text;
//Get the inputs
if (int.TryParse(txtNumberofreps.Text, out Numberofreps))
{
if (txtPhrase.Text == Phrase)
{
lstDisplay.Items.Add(txtPhrase.Text);
}
//Check to make sure its a positive value
while(Count >= 1)
{
//Display the number of reps
lstDisplay.Items.Add(txtPhrase.Text);
}
}
else
{
MessageBox.Show("Not a Positive Value");
}
You have in infinite loop since you are not changing the value of Count inside.
I would probably change the code to this:
private void btnDisplay_Click(object sender, EventArgs e)
{
// Delcare variables
int Numberofreps;
//Get the inputs
if (int.TryParse(txtNumberofreps.Text, out Numberofreps) && Numberofreps > 0)
// Note I've added a check that the Numberofreps is a positive integer.
{
while(Numberofreps > 0)
{
//Display the number of reps
lstDisplay.Items.Add(txtPhrase.Text);
Numberofreps--; // Note this line.
}
}
else
{
MessageBox.Show("Not a Positive Integer");
}
}
I suggest using for loop instead of while:
private void btnDisplay_Click(object sender, EventArgs e) {
int Numberofreps;
if (!int.TryParse(txtNumberofreps.Text, out Numberofreps))
MessageBox.Show("Not a integer Value");
else if (Numberofreps <= 0)
MessageBox.Show("Not a Positive Value");
else {
for (int i = 0; i < Numberofreps; ++i)
lstDisplay.Items.Add(txtPhrase.Text);
}
}
If you insist on while loop:
int i = 0;
while (i < Numberofreps) {
lstDisplay.Items.Add(txtPhrase.Text);
i += 1;
}
i am getting an invalid cast exception on this line
b = (int)dataGridView2.Rows[e.RowIndex].Cells[4].Value;
below is my code
private void dataGridView2_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
int a, b;
if (dataGridView2.Rows.Count > 0 && e.RowIndex >= 0 && e.ColumnIndex >= 0)
{
a = (int)dataGridView2.Rows[e.RowIndex].Cells[2].Value;
b = (int)dataGridView2.Rows[e.RowIndex].Cells[4].Value;
if (b > a)
{
MessageBox.Show("required quantity exceeds stock");
}
}
}
The NullReferenceException is due to the fact that the passed RowIndex index value might be invalid in some situations. Within such cases, the dataGridView2.Rows[e.RowIndex] will be doomed to utilize a null reference...
That InvalidCastException is probably due to that implicit casting, is which taken into account by you. You have mentioned nothing about the content of the datagridview cell, but if the casting logically would be possible in this scenario, you better to consider the static cast by Convert.ToInt32() method...
Finally below snippet might resolve your problem:
You need to handle the invalid values of the index to get rid of the exception.
private void dataGridView2_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
int a, b;
if (dataGridView1.Rows.Count > 0 && e.RowIndex >= 0 && e.ColumnIndex >= 0)
{
try
{
a = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[2].Value);
b = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[4].Value);
if (b > a)
{
MessageBox.Show("required quantity exceeds stock");
}
}
catch (NullReferenceException ex)
{
MessageBox.Show(ex.Message);
//Or whatever you've planned for...
}
}
}
I'm creating a calculator and I want to add validation code in it, so that if anything besides numbers is entered, an error message appears.
private void button4_Click(object sender, EventArgs e)
{
int R = Convert.ToInt32(textBox1.Text);
int I = Convert.ToInt32(textBox2.Text);
int number2;
if (int.TryParse(textBox1.Text, out number2))
{
int E = R - I;
textBox3.Text = E.ToString();
}
else
{
textBox2.Text = ("value entered is not whole number");
}
}
This is the code I am trying to use but it comes up with an error message when I enter a non-numeric value.
You are calling Convert.ToInt32 method before TryParse and that causes the exception. Don't do that, do the validation with TryParse.
private void button4_Click(object sender, EventArgs e)
{
int R, I;
if (int.TryParse(textBox1.Text, out R) &&
int.TryParse(textBox2.Text, out I))
{
int E = R - I;
textBox3.Text = E.ToString();
}
else
{
MessageBox.Show("You have entered an invalid value!");
}
}
Also you might consider using more descriptive variable names instead of E, R, I...
private void button4_Click(object sender, EventArgs e)
{
int R, I;
if (int.TryParse(textBox1.Text, out R)
&& int.TryParse(textBox2.Text, out I))
{
int E = R - I;
textBox3.Text = E.ToString();
}
else { textBox3.Text = ("value entered is not whole number"); }
}
Make sure you try to parse the strings into ints with TryParse always, rather than just converting immediately... if there are letters, the conversion fails.
private void button4_Click(object sender, EventArgs e)
{
int number1;
int number2;
if (int.TryParse(textBox1.Text, out number1) && int.TryParse(textBox2.Text, out number2))
{
//do your thang (subtraction, assigning the result to TextBox3)
//return
}
else
{
MessageBox.Show("Oh no you entered something that's not an int!");
}
}
I might also add that making the value of one of your input text boxes "Value entered is not a whole number" is kind of a weird UI experience. I'd mark the textbox in red or pop up a message box or something instead, leaving the entered value in the box, in case it was some really long number like 879320!78 where they accidentally entered a weird symbol or something.
private void button1_Click(object sender, EventArgs e)
{
double temp = double.Parse(textBox1.Text);
if (temp < 0)
{
label2.Text = "Freezing.";
}
if (temp > 40)
{
label2.Text = "Hot.";
}
else
{
label2.Text = "Moderate.";
}
}
Whenever converting user input, or any form of type String in to an object, I always like to use TryParse(...) as it provides you with better control if something isn't right.
double temp = 0.0d;
var converted = double.TryParse(textBox1.Text, out temp);
if (!converted) throw new Exception("Please enter a positive or negative temperature.");
if (temp < 0.0d)
{
// Freezing
}
else if (temp >= 0.0d && temp < 40.0d)
{
// Moderate
}
else if (temp >= 40.0d)
{
// Hot
}
The key is finding out what the value is being read in to temp. If its bringing in a negative number then I would recommend the code change below. What its really doing is if the 1st isnt true, then it checks the second, and finally it uses the third if neither are true.
private void button1_Click(object sender, EventArgs e)
{
double temp = double.Parse(textBox1.Text);
if (temp < 0)
{
label2.Text = "Freezing.";
}
else if (temp > 40)
{
label2.Text = "Hot.";
}
else
{
label2.Text = "Moderate.";
}
}
I am building a simple calculator( add + Multiply two numbers) using Windows Form Application
the code is working now but its when i try to validate it.
private void txtBtn1_Click(object sender, EventArgs e)
{
double a, b, c; // Declearing Variables
a = double.Parse(txtBox1.Text);
b = double.Parse(txtBox2.Text);
c = a + b;
txtLbl.Text = c.ToString();
}
I have tried this check:
if (int.TryParse(txtBox.Text, out int tempNum1) == false)
return;
and somthing like this:
if ((int.TryParse(txtBox1.Text, out int num1) == false) &&
(int.TryParse(txtBox1.Text, out int num2) == false))
MessageBox.Show("Please Enter a Number");
return;
Yes, you should use TryParse, e.g.
private void txtBtn1_Click(object sender, EventArgs e)
{
if (double.TryParse(txtBox1.Text, out double a) &&
double.TryParse(txtBox2.Text, out double b))
txtLbl.Text = (a + b).ToString(); // if both TextBoxes have valid values
else {
// At least one TextBox has invalid Text
txtLbl.Text = "???";
}
}
If you want to help user in error correction we can name the invalid argument and put a keyboard focus on it:
private void txtBtn1_Click(object sender, EventArgs e) {
if (double.TryParse(txtBox1.Text, out double a)) {
if (double.TryParse(txtBox2.Text, out double b))
txtLbl.Text = (a + b).ToString();
else {
if (txtBox2.CanFocus)
txtBox2.Focus();
MessageBox("Mot a Valid 'B' Number");
}
}
else {
if (txtBox1.CanFocus)
txtBox1.Focus();
MessageBox("Mot a Valid 'A' Number");
}
}
An alternative to avoid doing any manual validation is to swap your text box for a NumericUpDown component, it does all the validation for you and works the same as a textbox.
Or you could use regex.
string compare = "1234";
Regex regex = new Regex(#"^\d$");
if (regex.IsMatch(compare))
{
//It is only numbers
}