remove "$" when evaluating a textbox - c#

I am trying to get a messagebox to appear after a user closes my app. This messagebox lets the user know something based on their purchase. My problem is that my program crashes when it reads the "$" in the textbox. Here is where I'm currently at:
private void exitButton_Click(object sender, EventArgs e)
{
if
(MessageBox.Show("Are you sure you want to exit?",
"Confirm exit...",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question,
MessageBoxDefaultButton.Button2) == DialogResult.Yes)
{
decimal Discount;
Discount = decimal.Parse(postDiscountCostTextBox.Text);
if (Discount <= 999.99m)
{
MessageBox.Show("This amount qualifies for 'A-100' frequent flier miles.",
"",
MessageBoxButtons.OK);
}
}
{
this.Close();
}
}
The program worked perfectly when I removed the "$" from the textbox, however, it needs to be there in the final product. Any help would be appreciated.

Use this instead:
Discount = decimal.Parse(postDiscountCostTextBox.Text.Replace("$", ""));

What if the current culture on the system has a symbol other than a dollar sign for currency?
The correct approach is to specify the "Currency" NumberStyles and use TryParse() instead of Parse():
decimal Discount;
if (decimal.TryParse(postDiscountCostTextBox.Text, System.Globalization.NumberStyles.Currency, null, out Discount))
{
if (Discount <= 999.99m)
{
MessageBox.Show("This amount qualifies for 'A-100' frequent flier miles.",
"",
MessageBoxButtons.OK);
}
}
else
{
// ... invalid value in textbox ...
// Dipslay a MessageBox?
}

Related

Restricting texbox to not accept number format as ("010")

In my program, I have texboxes which I type the grade of a student. But I want to restrict the user to not digit a number in format like 010 or 020. Also, if the user digits 1 and change to another textbox it autommaticaly changes this digited number (1) to 1,0.
I tried this, but when it enters the second condition, it gives me an error.
private void txt3Bimestre_Validated(object sender, EventArgs e)
{
if (txt3Bimestre.Text[0].ToString().Equals("1") ||
txt3Bimestre.Text[0].ToString().Equals("2") ||
txt3Bimestre.Text[0].ToString().Equals("3") ||
txt3Bimestre.Text[0].ToString().Equals("4") ||
txt3Bimestre.Text[0].ToString().Equals("5") ||
txt3Bimestre.Text[0].ToString().Equals("6") ||
txt3Bimestre.Text[0].ToString().Equals("7") ||
txt3Bimestre.Text[0].ToString().Equals("8") ||
txt3Bimestre.Text[0].ToString().Equals("9"))
{
if (txt3Bimestre.Text[1].ToString().Equals(",") || txt3Bimestre.Text.Substring(0, 2) == "10")
{
}
}
else
{
MessageBox.Show("Formato Inválido", "Alertaa", MessageBoxButtons.OK, MessageBoxIcon.Error);
txt3Bimestre.Clear();
txt3Bimestre.Focus();
}
}
The problem here is that you're trying to force user to not input data as he/she wants on the textbox.
What I recommend u to to is to let user enter what he/she wants and, after leave the textbox or execute another event, test the data if it's the valid format or show the user an alert about his/her "mistake".
For example:
double value;
bool ok = double.TryParse(txt3Bimestre.Text, out value))
if (ok)
{
txt3Bimestre.Text = value.ToString("0.00");
}
else
{
MessageBox.Show("Formato Inválido", "Alerta", MessageBoxButtons.OK, MessageBoxIcon.Error);
txt3Bimestre.Clear();
txt3Bimestre.Focus();
}
If you have problems with , or . for decimals (culture related differences for decimals separator), look for CultureInfo.InvariantCulture.
Hope it helps.

How to allow only specific alphabets in a Textbox?

can I make my text box to allow only L & P for the starting two letters that is entered by a user.. example: LP12345678901. I hope the example makes the question specific...
I tried this
if(myTextBox.Text.StartsWith("LP"))
I tried regex too... but we cant be specific in alphabets right?
Try this code:
private void myTextBox_KeyDown(object sender, KeyEventArgs e)
{
if (myTextBox.Text.Length == 2)
{
if (myTextBox.Text.StartsWith("LP"))
{
//yourcode
}
else
{
myTextBox.Text = string.Empty;
}
}
}
This will help you.
function Valid() {
var re = "^[LP][0-9]{11}$";
var str = document.getElementById("txtTSection").value;
var myArray = str.match(re);
if (myArray == null) {
alert("Incorrect Format");
$("#txtTSection").css("border-color", "red");
return false;
}
else {
$('#txtTSection').css('border-color', '');
}
}
<asp:TextBox ID="txtTSection" runat="server" CssClass="form-control" TabIndex="1" MaxLength="13" onfocusout="Valid()" ></asp:TextBox>
This is not a technical solution, but rather an UX suggestion:
If I always have to enter "LP" as the first letters and I'm not allowed to enter different letters or numbers, then don't make me enter them every time. You already decided that "LP" are the first two letters. There is no point in me typing it again. I cannot gain anything good from it. Even if I'm perfect entering it, the best result I can achieve is "no error message".
If your first two letters have to be "LP" then put "LP" as a label before the textbox and make the user only enter the digits. When you are working with what the user entered, prefix it with "LP".
public static bool ValidateSerNo(string ser)
{
if (!string.IsNullOrEmpty(ser))
{
if (ser.Trim().Length == 11)
{
if (ser.Trim().ToUpper().Substring(0, 2) == "LP")
{
if (Microsoft.VisualBasic.Information.IsNumeric(ser.Substring(2, 9)))
{
return true;
}
}
}
}
return false;
}
private void btn_Save_Click(object sender, EventArgs e)
{
if ((BattVoltMmnt.ValidateSerNo(txtbox_Serialno.Text.Trim().ToUpper()) == false))
{ MessageBox.Show("Enter correct serial number");
}
}

Cant find the issue in this loop

I have a form that the user inputs values that i save in an array but when the user wants to cancel i want the user to be asked a final time if the user wants to go ahead and cancel a reservation. If the user declines this final time i want the program to go back to the GUI and focus on the textbox with all the rows of reservations and not do the cancelation but i show u the code i have written and it asks the user if they are sure and if not it still deletes the reservation and then focus on the textbox. What is wrong in my code?
public void Cancelreservation()
{
int index = lstReservations.SelectedIndex;
bool checkedindex = m_seatMngr.CheckIndex(index);
if (checkedindex)
{
if (!m_seatMngr.CancelSeat(index))
{
if (lstReservations.SelectedIndex == -1)
{
MessageBox.Show("You need to select a row.", "Error!",
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation,
MessageBoxDefaultButton.Button1);
lstReservations.Focus();
}
else
{
MessageBox.Show("The seat is not reserved! No need to cancel
reservation.", "Important Query",
MessageBoxButtons.OK);
lstReservations.Focus();
}
}
else
{
if (MessageBox.Show("Continue to cancel the reservation?",
"Important Query", MessageBoxButtons.YesNo)
== DialogResult.No)
{
lstReservations.Focus();
}
else
{
m_seatMngr.CancelSeat(index);
}
}
}
m_seatMngr
public bool CancelSeat(int index)
{
if (m_vacantList[index] == "Reserved")
{
m_nameList[index] = " - ";
m_priceList[index] = 0;
m_vacantList[index] = "Vacant";
return true;
}
else
{
return false;
}
}
Assuming that m_seatMngr.CancelSeat(index) is the method that actually cancels the seat, you are calling the method twice. The second if statement, half a dozen lines into your code, is this:
if (!m_seatMngr.CancelSeat(index))
... and it seems likely (given the above assumption) that this line will cancel the seat before you even display the MessageBox.
if (!m_seatMngr.CancelSeat(index))
{
// the rest of your code, which displays the messageboxes
}
This is always calling m_seatMngr.CancelSeat, before you've even displayed any messageboxes.

Decimal Point in Windows phone textfield

Hello Fellow C# and Windows phone developers,
For my windows phone application, I have a textfield requiring the user to enter their age. During debugging mode I entered the number .8. and clicked proceed and the application unexpectedly closed. What code do I need to add so I can post a message box informing the user that numbers with more than 1 decimal point is unacceptable. Please Help
Assuming the input is a string, try:
if (input.IndexOf('.') == -1 || input.LastIndexOf('.') == input.IndexOf('.'))
{
//good
}
else
MessageBox.Show("More than one decimal point");
A better way though would be to use TryParse which will check the number for formatting
float age;
if (float.TryParse(input, out age))
{
//good
}
else
MessageBox.Show("Invalid age.");
one way would be to limit the number of decimal place input to just one decimal place when user is entering their input.
this would be much better as it is real time instead of checking it at the end.
private void tbx_KeyDown(object sender, KeyEventArgs e)
{
//mark the sneder as a textbox control so we can access its properties
TextBox textBoxControl = (TextBox)sender;
//if there is already a decimals, do not allow another
if (textBoxControl.Text.Contains(".") && e.PlatformKeyCode == 190)
{
e.Handled = true;
}
}

C# - Correct validation for integers

I am currently building my project using windows forms and came across a minor "problem".
I have the user enter an hour which is stored as an int. I want to provide detailed feedback to the user so that they know exactly what they have done wrong should they cause an error.
If no value is given, a format exception is thrown.
If anything but an integer is given, a format exception is thrown.
This means I cannot directly tell the user that the new item could not be added due to EITHER 1) no value or 2) not an integer as they both use the same exception.
How can I solve this and what would be the best solution?
Many thanks.
Use the Int32.TryParse Method and check return value. You can simply check for no value entered before calling TryParse.
Here's an example of usage from MSDN:
int number;
bool result = Int32.TryParse(value, out number);
if (result)
{
Console.WriteLine("Converted '{0}' to {1}.", value, number);
}
else
{
if (value == null) value = "";
Console.WriteLine("Attempted conversion of '{0}' failed.", value);
}
some example code related to your question; note ValidateData in particular:
// called from ok button click or similar event
private void Accept()
{
if (!ValidateData())
return;
SaveData();
DialogResult = DialogResult.Ok;
Dispose();
}
private bool ValidateData()
{
int val;
if (string.IsNullOrEmpty(mTextBox.Text))
return FailValidation("Value can not be empty.", mTextBox);
if (!int.TryParse(mTextBox.Text, out val))
return FailValidation("Value was not an integer.", mTextBox);
return true;
}
// do something with the value if you need
private void SaveData()
{
}
// post a message to the user, and highlight the problematic control
// always evaluates to false
private bool FailValidation(string pMessage, Control pControl)
{
if (pControl != null)
{
pControl.Focus();
TextBox textBox = pControl as TextBox;
if (textBox != null)
textBox.SelectAll();
}
AlertBox(pMessage);
return false;
}
// quick alert message method
private void AlertBox(string pMessage)
{
return MessageBox.Show
(
pMessage,
Application.ProductName,
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation,
MessageBoxDefaultButton.Button1
);
}
Use int.TryParse to check format and than in success case check if integer is in valid range. Use String.IsNulOrEmpty to check for empty string.
If I can suggest a possible alternate solution... The best validation is preventing the bad input in the first place. Can you restrict the values the user can choose by using a control like a time picker or dropdown list? A dropdown list would still be keyboard friendly for powerusers, and it is a little easier for those who prefer a mouse. Wins for everyone.
This is well supported in Winforms. Use the Validating event to check the entry, the ErrorProvider component to report the error. A sample event handler:
private void textBox1_Validating(object sender, CancelEventArgs e) {
int hour;
e.Cancel = true;
if (textBox1.Text.Length == 0) errorProvider1.SetError(textBox1, "Can't be empty");
else if (!int.TryParse(textBox1.Text, out hour)) errorProvider1.SetError(textBox1, "Not a number");
else if (hour < 1) errorProvider1.SetError(textBox1, "Hour too small");
else if (hour > 24) errorProvider1.SetError(textBox1, "Hour too large");
else {
e.Cancel = false;
errorProvider1.SetError(textBox1, "");
}
}
Then you just need to check if all entries were satisfactory. Use the ValidateChildren() method in the dialog's OK button click event handler:
private void OKButton_Click(object sender, EventArgs e) {
if (ValidateChildren()) this.DialogResult = DialogResult.OK;
}

Categories

Resources