Why the result of IsDigit is not as intended - c#

In the below code if I enter numbers then it flashes error message instead it should flash in case of alphabets. I want to allow only numbers.
Also if I enter number and then any alphabet for e.g. 33er then the error msg is displayed and unless and untill I do not remove whole text the msg flashes, I have remove whole text and then I have enter numbers.
if (e.Handled != char.IsDigit(e.KeyChar))
{
errorProvider1.SetError(label1, "Allow Only Numeric Values !");
label1.Text = "Allow Only Numeric Values !";
}
else
{
errorProvider1.SetError(label1, "");
label1.Text = "";
}

I suggest not checking e.Handled but set it to true when required
if (char.IsDigit(e.KeyChar)) {
// Expected input, clear error messages
label1.Text = "";
}
else {
// Do not accept user input
e.Handled = true;
// Show error messages
label1.Text = "Allow Only Numeric Values !";
}
// Let's not repeat ourselves
errorProvider1.SetError(label1, label1.Text);

Related

Error Provider is not clearing itself even if the inputs are valid

I am using Windows Forms and Error Provider to validate my Textbox, the validation works as it intended but even if the input matches the validation, the Error Provider wont clear itself.
Here are some screenshots on the issue.
Here is my code, please advice me on how to fix it.
private void usernamet_Validating(object sender, CancelEventArgs e)
{
int username = usernamet.Text.Length;
ErrorProvider errorProvider = new ErrorProvider();
if (string.IsNullOrEmpty(usernamet.Text))
{
e.Cancel = true;
usernamet.Focus();
errorProvider.SetError(usernamet, "Username cannot be empty");
}
else if (username < 5 || username >= 20 )
{
e.Cancel = true;
usernamet.Focus();
errorProvider.SetError(usernamet, "Username must have more than 5 characters and less than 20 characters.");
}
else if (!Regex.IsMatch(usernamet.Text, #"^[a-zA-Z0-9#.]*$"))
{
e.Cancel = true;
usernamet.Focus();
errorProvider.SetError(usernamet, "Username cannot contain special characters.");
}
else
{
e.Cancel = false;
errorProvider.Clear();
errorProvider.SetError(usernamet, null);
}
}
https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.errorprovider.clear?view=netframework-4.7.2
Calling this method clears all property settings for this ErrorProvider, restoring the properties to their default values. To clear the error message, call the SetError method and pass in Empty for the String value. This removes the error glyph from the specified Control.

C# Try Catch not working. Wanting an error message to display when characters appear

I am trying to get a try-catch to work. I have made a website and part of it is to withdraw cash. When I put characters in the withdraw text box the display text is: "Transaction Completed - take your money."
This is my code. I am a beginner programmer and I do not know what to do. Variables that have not been explicitly declared in this code have been declared globally.
protected void continue_btn_Click(object sender, EventArgs e)
{
// if the input of amount is not empty assign amount to a conversion integer of txtAmount.Text
if (txtAmount.Text != "")
{
try
{
amount = Convert.ToInt32(txtAmount.Text);
hBos.setWithdrawls(amount);
}
catch (Exception ex)
{
resultLbl.Text = ex.Message;
}
}
//if a radio button has been selected convert the selected amount and assign it to the amount variable
else
{
amount = Convert.ToInt32(amountRadioBtnList.SelectedValue);
}
//if amount is not a multiple of 10 display an error message
if (amount % 10 != 0)
{
resultLbl.Text = "Error- amount must be a multiple of 10";
return;
}
else
{
//if euro is selected convert to euro with exchange rate
if (currencyRadioBtnList.SelectedValue == "Euro")
{
decimalAmount = amount / hBos.getExchangeRate();
}
//decimal amount is equal to amount
else
{
decimalAmount = amount;
}
}
//if decimalAmount is greater than 250
//Displays error message
if (decimalAmount > 250)
{
resultLbl.Text = "Error - cannot withdraw more than £250";
return;
}
//invoke withdraw method using login. pin and decimal amount as parameters
success = hBos.withdraw(login, pin, decimalAmount);
//if the withdraw fails
//Displays error message
if (success == false)
{
resultLbl.Text ="Error - Insufficient funds";
}
//display message that transaction is sucessful
else
{
resultLbl.Text = "Transaction Completed - take your money";
}
//if the print receipt check box has been checked
// save withdrawl to decimal amount
//Then go to withdrawl reciept webpage
if(checkPrintedRecipt.Checked == true)
{
Session["withdrawl"] = decimalAmount;
Response.Redirect("WithdrawlReceipt");
}
}
If you want to see the exception message, add a return after you set it:
// if the input of amount is not empty assign amount to a conversion integer of txtAmount.Text
if (txtAmount.Text != "")
{
try
{
amount = Convert.ToInt32(txtAmount.Text);
hBos.setWithdrawls(amount);
}
catch (Exception ex)
{
resultLbl.Text = ex.Message;
return;
}
}
Much as you already have for some other failure conditions. At the moment, your catch sets a message but the method then continues. And then it attempts to withdraw 0 and succeeds.
There are a few other issues with this code - amount and decimalAmount are apparently fields rather than local variables. That fact is hiding the fact that there appear to be control flow paths in this logic that fail to set decimalAmount to anything sensible and so the code will use whatever value was left over from previous usage. Prefer to declare your variables as close as possible to where they're used (use locals rather than fields, declare them inside the smallest block where they're needed) to uncover those types of errors.
Also, rather than Convert.ToInt32 inside a try/catch block, you might want to consider int.TryParse instead. That's a method that expects parsing to possibly fail and allows you to cope with that gracefully rather than having to throw and catch an exception.
Regardless of what you are doing in the rest of your code, your first if statement is ignored so the try-catch block is never observed.
The reason is that you have put some characters in your text box although your if block checks empty input!
When I put characters in the withdraw textbox the diplay text is:
Transaction Completed - take your money.
I think you were trying to code something like this :
if (txtAmount != null)
{
// try-catch block
}
This statement can be reasonable because it shows that you want to prevent the possible nullreferenceexception. The structre tha you have used here is a kind of contradiction

How do I get my StringBuilder to append correctly?

The following code is being used as a generic event handler for 16 digit buttons on a hexadecimal calculator (0-9, A-F).
The following instructions define what I need to be accomplishing:
If the calculator is in display mode when a digit is pressed, that digit will replace the current content of the display and place the calculator in input mode. If the calculator is in input mode, there are three cases:
If the content of the display is "0", the digit on the button pressed will replace the content of the display.
Otherwise, if the content of the display contains fewer than eight characters (because we are dealing with 32-bit words), the digit on the button pressed will be appended to the content of the display.
Otherwise, the button press is ignored.
One button press on my calculator will update the display correctly. However, if I press another button, instead of appending the StringBuilder with the new character, it will instead display a double character for the last button pressed. Eg. One press of 'C' will display a 'C'. A press of 'C' then say '8' will display '88'. Where is my problem here?
public void ProcessClick(object sender, EventArgs e)
{
StringBuilder _button = new StringBuilder();
_button.Append(((Button)sender).Text);
if (mode)
{
uxDisplay.Text = _button.ToString();
mode = false;
}
else
{
if (uxDisplay.Text == "0")
{
uxDisplay.Text = _button.ToString();
}
else if (uxDisplay.Text.Length < 8)
{
uxDisplay.Text = _button.Append(((Button)sender).Text).ToString();
}
else
{
return;
}
}
}
You appear to be appending the value of sender.Text twice.
Here:
_button.Append(((Button)sender).Text);
and here:
uxDisplay.Text = _button.Append(((Button)sender).Text).ToString();
You are also creating a new StringBuilder on each call to Process so you aren't persisting the last value (apart from in the uxDisplay control)
How about something simple like:
...
else if (uxDisplay.Text.Length < 8)
{
uxDisplay.Text += ((Button)sender).Text;
}
You are only appending a small number of strings so you won't really gain all that much performance from using a StringBuilder (especially if you create a new one on each call! :P )
You are appending the pressed button text to your StringBuilder object directly after its creation, that's why you get twice the character.
You can go with something simple like this:
public void ProcessClick(object sender, EventArgs e)
{
if (mode)
{
uxDisplay.Text = _button.ToString();
mode = false;
}
else
{
if (uxDisplay.Text == "0")
{
uxDisplay.Text = _button.ToString();
}
else if (uxDisplay.Text.Length < 8)
{
uxDisplay.Text += ((Button)sender).Text;
}
else
{
return;
}
}
}

C# Validating event: test for blank textbox and number validation?

So I'm trying to create a validating event that makes sure a textbox isn't empty and that the number entered doesn't exceed 2000. I've posted what I have but every time I run it I get a message that the exception wasn't handled because the "kwh = decimal.Parse(khtextBox.Text)" input is not in the correct format. The way I have it, the validating works if the number exceeds 2000, but not if the textbox is blank. What am I doing wrong? Also new to programming so please explain like you're talking to a 3 year old! Thanks :)
private void khtextBox1_Validating(object sender, CancelEventArgs e)
{
decimal kwh;
kwh = decimal.Parse(khtextBox1.Text);
bool blank = false;
if (blank)
{
MessageBox.Show("Please enter a valid number.");
}
if (kwh > 2000)
{
MessageBox.Show("Kilowatt-Hours cannot exceed 2000.");
e.Cancel = true;
}
}
Try using the decimal.TryParse method, which try to convert the string to a decimal and returns a bool value if the conversion succeed, for sample:
decimal kwh;
if (!decimal.TryParse(khtextBox1.Text, out kwh)) // check if the conversion has failed
{
MessageBox.Show("Please enter a valid number.");
e.Cancel = true;
}
else // conversion ok, you can use the kwh value
{
if (kwh > 2000)
{
MessageBox.Show("Kilowatt-Hours cannot exceed 2000.");
e.Cancel = true;
}
}
You clearly mention yourself what the issue is. The input has to be something that could be converted to decimal some number.
It seems like an issue with incorrect input. Could you try using TryParse instead or you could simply change that second 'if' block to 'else if'.
decimal outputKWH;
kwh = decimal.TryParse(khtextBox.Text, out outputKWH)

C# TextBox to int() not working when no value is entered

I have just started programming in C#. I am trying to convert a string to int. Like this:
int.Parse(textBox1.Text);
This is working fine when I enter a value but this is giving me exception when nothing is entered and I press the button. What should I do? Is there a function to solve this? Thanks
Use int.TryParse instead, it doesn't throw exception if the parsing fails.
Converts the string representation of a number to its 32-bit signed integer equivalent. A return value indicates whether the conversion succeeded.
int number;
bool isValid = int.TryParse(textBox1.Text, out number);
if(isValid)
{
// parsing was successful
}
One way to approach this is by using int.tryParse() instead of just int.Parse(). You can then check the result to see if the input was in the correct format.
Here is a sample:
int userInput;
if(!int.TryParse(textBox1.Text, out userInput))
{
//error in input here
}
After executing, if int.TryParse() returns true, then you will have a valid value in the userInput variable.
Alternatively you can wrap it in a try-catch, but it is better to attempt the parse and handle it without exceptions if possible.
Put this following code under your button event. It will make sure that the text/numbers entered into the textbox are able to be converted into an integer. Also, it will make sure that the textbox has numbers/text entered.
if (textBox1.Text != "")
{
try
{
Convert.ToInt32(textBox1.Text);
}
catch
{
/*
Characters were entered, thus the textbox's text cannon be converted into an integer.
Also, you can include this line of code to notify the user why the text is not being converted into a integer:
MessageBox.Show("Please enter only numbers in the textbox!", "PROGRAM NAME", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
*/
}
}
/*
else
{
MessageBox.Show("Please enter numbers in the textbox!", "PROGRAM NAME", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
*/
This is simple. You can do this on your button click event:
int number;
if (int.TryParse(textbox1.Text, out number))
{
// number is an int converted from string in textbox1.
// your code
}
else
{
//show error output to the user
}
Try below given solution
<script type="text/javascript">
function myFunction() {
alert('Please enter textbox value.');
}
</script>
And in the button click event use below given logic.
if (TextBox1.Text == "")
{
//Call javascript function using server side code.
ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "myFunction()", true);
}
else
{
int value;
value = int.Parse(TextBox1.Text);
}

Categories