Issues with > and < in C# - c#

I have an issue with a small piece of code I've made.
For the code I have to make a small check. When the value of _mmdTextBox is bigger then 1999 it should give a MessageBx.Show("Value to high").
If the value is smaller then 0 there should be a MessageBox.Show("Value to low").
This is what I have made so far:
private void _mmdButton_Click(object sender, EventArgs e)
{
var value = _mmdTextBox.Text;
if (value > 1999 && value < 0)
{
MessageBox.Show("Value is to high");
}
else
{
// action
}
}
This is the error that I get when I do it like the code above:
Error 1 Operator '>' cannot be applied to operands of type 'string' and 'int'

int value;
if(Int32.TryParse(_mmdTextBox.Text, out value)
{
if (value > 1999)
{
MessageBox.Show("Value is too high");
}
else if(value < 0)
{
MessageBox.Show("Value is too low");
}
else
{
// action
}
}
else
{
// not a number
}

TextBox.Text returns string. So your value will be string. You can't compare string with an integer using < or > operators.
From MSDN;
All numeric and enumeration types define....
Try to convert your value to int if it is available.
int value;
if(Int32.TryParse(_mmdTextBox.Text, out value)
{
if (value > 1999)
{
MessageBox.Show("Value is too high");
}
if(value < 0)
{
MessageBox.Show("Value is too low");
}
}

C# is an strongly typed language and if you want to compare 2 value . They should be the same type . So you need to be convert text box text to int also you need a validation to be insure that the value which coming from text bot is int ok
I thought this will help full for you

Your if statement could be changed to look like this:
var value = Convert.ToInt32(_mmdTextBox.Text); //Convert to int in order to compare against an int
if (value > 1999)
{
MessageBox.Show("Value is to high");
}
else if (value < 0)
{
MessageBox.Show("Value is to low");
}
else
{
//Action
}
You are comparing the value as type string to type int.
int.TryParse() would be a better option for the int conversion as the user could enter anything. (Like in Erno De Weerd's answer)

You are comparing _mmdTextBox.Text which is string to constant of type int! It is impossible!
You should convert the former to int:
int value;
if(!int.TryParse(_mmdTextBox.Text, out value))
{
MessageBox.Show("Bad integer value in textbox");
return;
}

How can something be > 1999 AND < 0 ?
TryParse might be better for your conversion but this should work:
private void _mmdButton_Click(object sender, EventArgs e)
{
var value = Convert.ToInt32(_mmdTextBox.Text);
if (value > 1999)
{
MessageBox.Show("Value is too high");
}
else if (value < 0)
{
MessageBox.Show("Value is too low");
}
else
{
MessageBox.Show("Value is ok");
}
}

Your problem ist, that value is a string and not a number. You can use Parse or TryParse to solve it.
If you want to use .TryParse() make it look like this example from MSDN:
int number;
bool result = Int32.TryParse(value, out number);
if (result)
{
if (number > 1999 || number < 0)
{
MessageBox.Show("Value is invalid");
}
else
{
// action
}
}
else
{
//Show that the input is not a numeric value
}

Try it for instead of your if condition
if (Convert.ToInt32(value) > 1999 && !Convert.ToInt32(value)< 0)

Related

Exception Handling C#

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
}

Why am I getting a format exception in this C# code?

I am working on a Windows Form application. I am parsing an XML file and doing some queries. For example, in this case I am trying to find all users weighing between 55 and 100. For some reason, when I run this code, I get a format exception unhandled. Why am I getting a format exception. I have indicated the breakpoint where the exception occurs. I think the problem is a syntactical error.
Thanks for your help.
private bool UserWeighsBetween55and100(IEnumerable<XElement> paramsList) {
bool result = false;
foreach (XElement parameter in paramsList) {
if (parameter.Attribute("name").Value == "Weight") {
--->HERE if ((Int32.Parse(parameter.Attribute("value").Value) > 55) &&
(Int32.Parse(parameter.Attribute("value").Value) < 100)){
return true;
}
}
}
return result;
}
Convert your value once instead of converting same value two time.
Try to do like this.
int iValue = 0;
if (Int.TryParse(parameter.Attribute("value").Value, out iValue)) //If the value converted
{
if (iValue > 55 && iValue < 100)
{
return true;
}
}
else //Failed to convert value into int datatype
{
//Code here if conversion faild
}
if the parameter.Attribute("value").Value is containing non-numeric value then it wont convert in int datatype.
Instead of using the "Parse" method, use the tryParse.
In your case, it would look like :
foreach (XElement parameter in paramsList) {
if (parameter.Attribute("name").Value == "Weight") {
int value;
if(!Int32.TryParse(parameter.Attribute("value").Value, out value)){
//Not a number, handle this case
}
if ((value > 55) && (value < 100)){
return true;
}
return result;
}
I will be answering my question because I found out my mistake and I hope it would help everybody reading this post.
The problem with using Int32.Parse() was that while I was parsing the XML file, I didn't pay attention to the values of type double.
The fix for this code would be as follows:
private bool UserWeighsBetween55and100(IEnumerable<XElement> paramsList) {
bool result = false;
foreach (XElement parameter in paramsList) {
if (parameter.Attribute("name").Value == "Weight") {
if ((parameter.Attribute("value").Value)!=null) {
if ((Convert.ToDouble(parameter.Attribute("value").Value) > 55) && (Convert.ToDouble(parameter.Attribute("value").Value) < 100)) {
return true;
}
}
}
}
return result;
}

Checking whether a text box contain only digits

I am done with this problem(using an alternative method). But still don't know why the following method is not working. Please help
Aim: when leave from a text box
check whether it contain only digits-then allow to leave.
If not show an error provider.
check whether string length is not more than 7 and not 0 -then allow to leave.
if not show an error provider.
Code that doesn't seem working is given below! :
private void textBox24_Validating(object sender, CancelEventArgs e)
{
bool result = true;
foreach (char y in textBox24.Text)
{
while (y < '0' || y > '9')
result = false;
}
if (result == false)
{
errorProvider4.SetError(textBox24, "Enter digits only");
textBox24.Focus();
}
else if (textBox24.Text.Length == 0)
{
errorProvider4.SetError(textBox24, "Enter the value");
textBox24.Focus();
}
else if (textBox24.Text.Length > 7)
{
errorProvider4.SetError(textBox24, "Maximum length is 7 digits");
textBox24.Focus();
}
else
errorProvider4.Clear();
}
problem with this code:
when I enter input other than digits, it gets stuck.
May be this wont be a big question. However help me.
code that now I am using:
private void textBox24_Validating(object sender, CancelEventArgs e)
{
int check = 123;
bool result = int.TryParse(textBox24.Text, out check);
if (result == false)
{
errorProvider4.SetError(textBox24, "Only digits are allowed");
textBox24.Focus();
}
else if (textBox24.Text.Length > 7)
{
errorProvider4.SetError(textBox6, "Invalid value");
textBox24.Focus();
}
else
errorProvider4.Clear();
}
inside while loop you have condition if true you set the result as true but loop running forever because condition again true.
foreach (char y in textBox24.Text)
{
while (condition) // this is run forever if true
result = false;
}
you can use break; if true case like below
foreach (char y in textBox24.Text)
{
while (condition){
result = false;
break;
}
}
Few more Suggestion..
TextBox control having property called MaxLength you can set it as 7 to limit user input up to 7 characters
if you need to allow only digits don't use int.TryParse method. if input with decimal points will pass the validation.
to check string contains only digits you can use code like if (textBox1.Text.ToCharArray().Any(c=>!Char.IsDigit(c)))
if validation fail you need to set e.Cancel = true;

Validating a Textbox field for only numeric input.

I have created a form-based program that needs some input validation. I need to make sure the user can only enter numeric values within the distance Textbox.
So far, I've checked that the Textbox has something in it, but if it has a value then it should proceed to validate that the entered value is numeric:
else if (txtEvDistance.Text.Length == 0)
{
MessageBox.Show("Please enter the distance");
}
else if (cboAddEvent.Text //is numeric)
{
MessageBox.Show("Please enter a valid numeric distance");
}
You may try the TryParse method which allows you to parse a string into an integer and return a boolean result indicating the success or failure of the operation.
int distance;
if (int.TryParse(txtEvDistance.Text, out distance))
{
// it's a valid integer => you could use the distance variable here
}
If you want to prevent the user from enter non-numeric values at the time of enter the information in the TextBox, you can use the Event OnKeyPress like this:
private void txtAditionalBatch_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsDigit(e.KeyChar)) e.Handled = true; //Just Digits
if (e.KeyChar == (char)8) e.Handled = false; //Allow Backspace
if (e.KeyChar == (char)13) btnSearch_Click(sender, e); //Allow Enter
}
This solution doesn't work if the user paste the information in the TextBox using the mouse (right click / paste) in that case you should add an extra validation.
Here is another simple solution
try
{
int temp=Convert.ToInt32(txtEvDistance.Text);
}
catch(Exception h)
{
MessageBox.Show("Please provide number only");
}
You can do it by javascript on client side or using some regex validator on the textbox.
Javascript
script type="text/javascript" language="javascript">
function validateNumbersOnly(e) {
var unicode = e.charCode ? e.charCode : e.keyCode;
if ((unicode == 8) || (unicode == 9) || (unicode > 47 && unicode < 58)) {
return true;
}
else {
window.alert("This field accepts only Numbers");
return false;
}
}
</script>
Textbox (with fixed ValidationExpression)
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator6" runat="server" Display="None" ErrorMessage="Accepts only numbers." ControlToValidate="TextBox1" ValidationExpression="^[0-9]*$" Text="*"></asp:RegularExpressionValidator>
I agree with Int.TryParse but as an alternative you could use Regex.
Regex nonNumericRegex = new Regex(#"\D");
if (nonNumericRegex.IsMatch(txtEvDistance.Text))
{
//Contains non numeric characters.
return false;
}
You can do this way
// Check if the point entered is numeric or not
if (Int32.TryParse(txtEvDistance.Text, out var outParse))
{
// Do what you want to do if numeric
}
else
{
// Do what you want to do if not numeric
}
I have this extension which is kind of multi-purpose:
public static bool IsNumeric(this object value)
{
if (value == null || value is DateTime)
{
return false;
}
if (value is Int16 || value is Int32 || value is Int64 || value is Decimal || value is Single || value is Double || value is Boolean)
{
return true;
}
try
{
if (value is string)
Double.Parse(value as string);
else
Double.Parse(value.ToString());
return true;
}
catch { }
return false;
}
It works for other data types. Should work fine for what you want to do.
if (int.TryParse(txtDepartmentNo.Text, out checkNumber) == false)
{
lblMessage.Text = string.Empty;
lblMessage.Visible = true;
lblMessage.ForeColor = Color.Maroon;
lblMessage.Text = "You have not entered a number";
return;
}
Here's a solution that allows either numeric only with a minus sign or decimal with a minus sign and decimal point. Most of the previous answers did not take into account selected text. If you change your textbox's ShortcutsEnabled to false, then you can't paste garbage into your textbox either (it disables right-clicking). Some solutions allowed you to enter data before the minus. Please verify that I've caught everything!
private bool DecimalOnly_KeyPress(TextBox txt, bool numeric, KeyPressEventArgs e)
{
if (numeric)
{
// Test first character - either text is blank or the selection starts at first character.
if (txt.Text == "" || txt.SelectionStart == 0)
{
// If the first character is a minus or digit, AND
// if the text does not contain a minus OR the selected text DOES contain a minus.
if ((e.KeyChar == '-' || char.IsDigit(e.KeyChar)) && (!txt.Text.Contains("-") || txt.SelectedText.Contains("-")))
return false;
else
return true;
}
else
{
// If it's not the first character, then it must be a digit or backspace
if (char.IsDigit(e.KeyChar) || e.KeyChar == Convert.ToChar(Keys.Back))
return false;
else
return true;
}
}
else
{
// Test first character - either text is blank or the selection starts at first character.
if (txt.Text == "" || txt.SelectionStart == 0)
{
// If the first character is a minus or digit, AND
// if the text does not contain a minus OR the selected text DOES contain a minus.
if ((e.KeyChar == '-' || char.IsDigit(e.KeyChar)) && (!txt.Text.Contains("-") || txt.SelectedText.Contains("-")))
return false;
else
{
// If the first character is a decimal point or digit, AND
// if the text does not contain a decimal point OR the selected text DOES contain a decimal point.
if ((e.KeyChar == '.' || char.IsDigit(e.KeyChar)) && (!txt.Text.Contains(".") || txt.SelectedText.Contains(".")))
return false;
else
return true;
}
}
else
{
// If it's not the first character, then it must be a digit or backspace OR
// a decimal point AND
// if the text does not contain a decimal point or the selected text does contain a decimal point.
if (char.IsDigit(e.KeyChar) || e.KeyChar == Convert.ToChar(Keys.Back) || (e.KeyChar == '.' && (!txt.Text.Contains(".") || txt.SelectedText.Contains("."))))
return false;
else
return true;
}
}
}
To check if the value is a double:
private void button1_Click(object sender, EventArgs e)
{
if (!double.TryParse(textBox1.Text, out var x))
{
System.Console.WriteLine("it's not a double ");
return;
}
System.Console.WriteLine("it's a double ");
}
I know this is an old question but I figured out I should pitch my answer anyways.
The following snippet iterates through each character of the text and uses the IsNumber() method, which returns true if the character is a number and false the other way, to check if all the characters are numbers. If all are numbers, the method returns true. If not it returns false.
using System;
private bool ValidateText(string text){
char[] characters = text.ToCharArray();
foreach(char c in characters){
if(!char.IsNumber(c))
return false;
}
return true;
}
Use Regex as below.
if (txtNumeric.Text.Length < 0 || !System.Text.RegularExpressions.Regex.IsMatch(txtNumeric.Text, "^[0-9]*$")) {
MessageBox.show("add content");
} else {
MessageBox.show("add content");
}

Not allow zero in textbox

I need a textbox which only the user can permit to enter integers. But the user can't enter zero. i.e, he can enter 10,100 etc. Not 0 alone.
How can I make event in KeyDown?
The way you plan to do this, is very annoying for a user. You're guessing what a user wants to enter, and act upon your guess, but you can be so wrong.
It also has holes, for example, a user can enter "10" and then delete the "1". Or he could paste in a "0" -- you do allow paste, don't you?
So my solution would be: let him enter any digit he likes, any way he likes, and validate the input only after he finished, for example, when the input loses focus.
Why not using a NumericUpDown and make the following settings:
upDown.Minimum = 1;
upDown.Maximum = Decimal.MaxValue;
Use int.TryParse to convert the text into a number and check if that number is not 0. Use the Validating event for the check.
// this goes to you init routine
textBox1.Validating += textBox1_Validating;
// the validation method
private void textBox1_Validating(object sender, CancelEventArgs e)
{
if (textBox1.Text.Length > 0)
{
int result;
if (int.TryParse(textBox1.Text, out result))
{
// number is 0?
e.Cancel = result == 0;
}
else
{
// not a number at all
e.Cancel = true;
}
}
}
EDIT:
Okay, since you use WPF you should take a look at how to implement validation the WPF way. Here is a validation class that implements the above logic:
public class StringNotZeroRule : ValidationRule
{
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
if (textBox1.Text.Length == 0)
return new ValidationResult(true, null);
int result;
if (int.TryParse(textBox1.Text, out result))
{
// number is 0?
if (result == 0)
{
return new ValidationResult(false, "0 is not allowed");
}
}
else
{
// not a number at all
return new ValidationResult(false, "not a number");
}
return new ValidationResult(true, null);
}
}
This is another variation on the theme:
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
char newChar = Convert.ToChar(e.KeyValue);
if (char.IsControl(newChar))
{
return;
}
int value;
e.SuppressKeyPress = int.TryParse((sender as TextBox).Text + newChar.ToString(), out value) ? value == 0 : true;
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (textBox1.Text == "" && e.KeyChar == '0')
{
e.Handled = true;
return;
}
if (e.KeyChar < '0' || e.KeyChar > '9')
{
e.Handled = true;
return;
}
}
not nice but it works

Categories

Resources