Is there something wrong with my If Statements? - c#

This function checks if the values in the text boxes are parsable or not. This method is called upon in the method below this.
private bool CheckForInvalidEntries()
{
bool ParseIsSuccessfull; int result; //These 2 variables are for trying to parse the entries in the Stat text boxes
bool ContainsInvalidEntry = false;
if ((ParseIsSuccessfull = int.TryParse(P1STRtextbox.Text, out result)) == false)
{
ContainsInvalidEntry = true;
}
else if ((ParseIsSuccessfull = int.TryParse(P1DEXtextbox.Text, out result)) == false)
{
ContainsInvalidEntry = true;
}
else if ((ParseIsSuccessfull = int.TryParse(P1VIGtextbox.Text, out result)) == false)
{
ContainsInvalidEntry = true;
}
else if ((ParseIsSuccessfull = int.TryParse(P1RMtextbox.Text, out result)) == false)
{
ContainsInvalidEntry = true;
}
else if ((ParseIsSuccessfull = int.TryParse(P1BMtextbox.Text, out result)) == false)
{
ContainsInvalidEntry = true;
}
else ContainsInvalidEntry = false;
return ContainsInvalidEntry;
}
This function is the event where if the process stat points button is clicked
private void p1ProcessPointsBtn_Click(object sender, EventArgs e)
{
bool EntriesAreInvalid = new bool();
EntriesAreInvalid = CheckForInvalidEntries();
if (EntriesAreInvalid == true)
{
P1STRtextbox_TextChanged(sender, e);
P1DEXtextbox_TextChanged(sender, e);
P1VIGtextbox_TextChanged(sender, e);
P1RMtextbox_TextChanged(sender, e);
P1BMtextbox_TextChanged(sender, e);
}
else
{
MessageBox.Show("Success");
}
FUNCTIONALITY: When the user presses the "Process Stat Points" button, the program checks whether the entries in the 5 text boxes are able to be parsed(in the CheckForInvalidEntries method). It then returns a bool value to the EntriesAreInvalid variable(in the p1ProcessPointsBtn_Click method). If the entries are not parsable, do action A, if the entries are parsable, do action B.
PROBLEM: If the numbers are parsable in all the text boxes, I don't get a result. Im only getting results if the text boxes are not parsable. I think it has something to do with the if statements within the "CheckForInvalidEntries" method. What can I do to fix my problem. Your time and effort is greatly appreciated!

TryParse sets Result to zero if the conversion fails. Since you keep calling TryParse you keep resetting Result.
If you only want to check for parsing errors, this ought to work:
ContainsInvalidEntry = false;
ContainsInvalidEntry |= !int.TryParse(P1STRtextbox.Text, out result));
ContainsInvalidEntry |= !int.TryParse(P1DEXtextbox.Text, out result));
ContainsInvalidEntry |= !int.TryParse(P1VIGtextbox.Text, out result));
ContainsInvalidEntry |= !int.TryParse(P1RMtextbox.Text, out result));
ContainsInvalidEntry |= !int.TryParse(P1BMtextbox.Text, out result));
return ContainsInvalidEntry;
Aside: Comparing boolean values to true and false is a bit (Pardon the pun.) strange. if ( ( ParsedOkay == ( false ) ) ) may be valid, but if ( !ParsedOkay ) is more common.

i was too confused by your code. But i think this will help you. If i got you right you wanted to check if all the text in the textboxes is parsable to an int. And if it is so you wanted to print out "succes";
private bool isParsable(TextBox t) //takes a TextBox as paramater and returns true if
{ // its parsable
int i = 4;
if (int.TryParse(t.Text, out i) == true)
return true;
else
return false;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
if(isParsable(tbox1) == true && isParsable(tbox2) == true) //if every textbox
{ //is parsable print
tblock1.Text = "succes";
}
else
{
tblock1.Text = "error";
}
}

First of all you don't need to write your if statements like this, it's too messy and unnecessary. Complex code always prone to error,
Instead of this:
if ((ParseIsSuccessfull = int.TryParse(P1STRtextbox.Text, out result)) == false)
You could write:
if(!int.TryParse(P1STRtextbox.Text, out result))
Because TryParse already returning a bool result.If you want check whether it's false just put negation operator (!) beginning of your statement. Also you can write a simple method to check whether your texts are parsable or not:
static bool CheckForParse(params string[] values)
{
int x;
if(values.Lenght > 0)
{
for(int i=0; i<values.Lenght;i++)
{
if(!int.TryParse(values[i], x)) return false;
}
return true;
} else { return false }
return false;
}
And you can call it like this:
bool result = CheckForParse(P1STRtextbox.Text,
P1DEXtextbox.Text,
P1VIGtextbox.Text,
P1RMtextbox.Text,
P1BMtextbox.Text);
if(result)
{
P1STRtextbox_TextChanged(sender, e);
P1DEXtextbox_TextChanged(sender, e);
...
}

Related

Picker gives me an ArgumentOutOfRangeException, why is this happening?

I need my picker to hide elements if authorization == true.
private async void Picker_Unfocused(object sender, FocusEventArgs e)
{
try
{
await DisplayAlert("try", picker.SelectedIndex.ToString(), "OK");
if (response.domains[picker.SelectedIndex].authorization == true)
{
userNameEntry.IsVisible = false;
passwordEntry.IsVisible = false;
userLabel.IsVisible = false;
}
else
{
userNameEntry.IsVisible = true;
passwordEntry.IsVisible = true;
userLabel.IsVisible = true;
}
}
catch(System.ArgumentOutOfRangeException)
{
await DisplayAlert("catch", picker.SelectedIndex.ToString(), "OK");
}
}
This won't help. I get an ArgumentOutOfRangeException. Does anyone know why? It is important to me that this works.
Edit: Code is now current code. displayalerts just give me 0 if I select the first item, 1 if I select the second, etc. I still don't know what's going on. If the value of SelectedIndex is 0(or whatever I select) I shouldn't get an ArgumentOutOfRangeException, right?
When the picker is not yet initialized or can view a null value and is thus empty, the SelectedIndex property will give you a value of -1. This value is not valid for use in an array.
You should enrich your code to account for this possibility, for instance like this:
if (picker.SelectedIndex > -1 && response.domains[picker.SelectedIndex].authorization == true)
{
userNameEntry.IsVisible = false;
passwordEntry.IsVisible = false;
userLabel.IsVisible = false;
}
else
{
userNameEntry.IsVisible = true;
passwordEntry.IsVisible = true;
userLabel.IsVisible = true;
}

C# if statement to test if value is not a number

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!"); }

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;

Error when assigning a boolean value

I am getting an error while assigning a value.
My code is:
protected bool ValidateProfile()
{
bool blnFirstName = false;
bool blnLastName = false;
bool blnEMail = false;
//(error on line below: "The left-hand side of an assignment must be a variable, property or indexer")
ValidateProfile() = false;
if txtFName != ""
blnFName = true;
if txtLName != ""
blnLName = true;
if txtEMail != ""
blnEMail = true;
if (blnFName) && (blnLName) && (blnEMail))
ValidateProfile = true;
}
How do I assign a boolean value to ValidateProfile ?
Thanks
You want
return false;
In C#, we don't assign values to the function name in order to return a value.
If you want to set the return value at a different point in time from when you return from the method, then you should do something like this:
bool retVal; // Defaults to false
if (condition)
retVal = true;
if (otherCondition)
retVal = false;
if (thirdCondition)
retVal = true;
return retVal;
You can't assign a value to a function. You need return false;
As others have pointed out, in C# you use return instead of MyFunction = x. In this scenario, you can assign the result of your final check to a boolean and return it:
bool retVal = (blnFName) && (blnLName) && (blnEMail);
return retVal;
Alternatively, you could just skip the assignment altogether:
return (blnFName) && (blnLName) && (blnEMail);
EDIT: I noticed you are using hungarian notation, which implies that txtFName is a TextBox. Keep in mind that C# doesn't have default properties like VB. If it is a TextBox, it will never equal "", because it's not of type System.String. I'm guessing you actually wanting to evaluate txtFName.Text
Change that last line to:
return false;
Although it seems you're always returning false here. Is there an option to return true?
Just a side note besides all the returns...
You may want to change this:
if txtFName != ""
To check if the String.IsEmptyOrNull(txtFName.Text)
Or at least initialize your variables to either null or String.Empty.
Just an FYI though.
You want to return false
Alright, taking the code you posted:
protected bool ValidateProfile()
{
return !String.IsNullOrEmpty(txtFName) && !String.IsNullOrEmpty(txtLName) && !String.IsNullOrEmpty(txtEMail);
}
Or
protected bool ValidateProfile()
{
bool returnValue = true;
if(String.IsNullOrEmpty(txtFName))
{
returnValue=false;
}
else if(String.IsNullOrEmpty(txtLName))
{
returnValue = false;
}
else if(String.IsNullOrEmpty(txtEMail))
{
returnValue = false;
}
return returnValue;
}
Though you could just return false as soon as you find an invalid field.
Not a C# programmer, but can't you just write:
return (txtFName != "") && (txtLName != "") && (txtEMail != "");
for the body of the function?

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