So I have a Subtotal TextBox where an amount like $546.75 can be entered. Now, I want to make sure that only numbers, ONE decimal, One Dollar Symbol and commas allowed only every 3 places (100,000,000). Is this possible? Maybe not the commas, but at least the numbers, decimal, and dollar symbol.
Why you dont put the money sign "$" out side of the textBox (create a label just infrontof textBox), then you will not have to worry about this character, but only about numbers. And it looks better (in my opinion).
Then you can use this code:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar != (Char)Keys.Back) //allow backspace (to delete)
{
e.Handled = !char.IsNumber(e.KeyChar);
}
}
All validation should be performed manually on KeyPress event.
Here described validation for numeric values values. You will need to check the '$' sign and decimals additionally.
I think you are using WinForms and not WPF. If that is the case then you could use System.Windows.Forms.ErrorProvider (you can drag-drop one from toolbox to your form) along with regular expressions to do the validation.
WARNING: The regex pattern string below may not do exactly you want but hopefully conveys the idea.
Some match examples... "$4,000.00", "-$4000.00", "-$400.00"
private void textBox1_Validating(object sender, CancelEventArgs e)
{
string error = null;
string pattern = #"^\$?\-?([1-9]{1}[0-9]{0,2}(\,\d{3})*(\.\d{0,2})?|[1-9]{1}\d{0,}(\.\d{0,2})?|0(\.\d{0,2})?|(\.\d{1,2}))$|^\-?\$?([1-9]{1}\d{0,2}(\,\d{3})*(\.\d{0,2})?|[1-9]{1}\d{0,}(\.\d{0,2})?|0(\.\d{0,2})?|(\.\d{1,2}))$|^\(\$?([1-9]{1}\d{0,2}(\,\d{3})*(\.\d{0,2})?|[1-9]{1}\d{0,}(\.\d{0,2})?|0(\.\d{0,2})?|(\.\d{1,2}))\)$";
if (!Regex.IsMatch(textBox1.Text, pattern))
{
error = "Please enter a US currency value.";
e.Cancel = true;
}
errorProvider1.SetError((Control)sender, error);
}
There are a number of articles on numeric textboxes
Numeric TextBox
http://www.daniweb.com/software-development/csharp/threads/95153
http://www.codeproject.com/KB/vb/NumericTextBox.aspx
I use this one in my projects
http://www.codeproject.com/KB/edit/ValidatingTextBoxControls.aspx
//tb - is the name of text box
private void tb_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
char[] inputChar = e.Text.ToCharArray();
if (char.IsNumber(inputChar[0]))
{
e.Handled = false;
}
else
{
e.Handled = true;
}
// another method.
if (char.IsDigit(inputChar[0]))
{
e.Handled = false;
}
else
{
e.Handled = true;
}
}
Have you tried Ajax Controls?
http://www.aspsnippets.com/Articles/ASPNet-AJAX-FilteredTextBoxExtender-Control-Example.aspx
Simples. :)
Related
I have a project in C#.net using a WPF textbox that validates a character like * as the first character entered. If this character is entered, the rest of the text is good but I cannot show nor use the character. How can I remove the character from the string early enough to not show it? I've attempted using the KeyDown event but while the event is active, there is no data to remove. And if I use the KeyUp event the data is shown for a second. I've previously used a KeyPress event in VB6 to achieve this which worked because the value was simultaneously in the code but not in the textbox. As far as I can tell a WPF textbox does not have this event. What can I do?
Code:
private void UserInput_KeyUp(object sender, KeyEventArgs e)
{
//get ascii value from keyboard input
int Ascii = (int)e.Key;
//get char value to know what to remove as a string
char CharAscii = (char)Ascii;
If(Ascii == InputPrefix)
{
PrefixValidated = true;
UserInput.Text = UserInput.Text.Replace(CharAscii.ToString(), string.Empty);
}
}
The same code is in the KeyDown event and I've tried it using one or the other and both.
it may be a bit of a rough solution but you could use a PreviewTextInupt event I belive.
private bool PrefixValidated = false;
private string CheckUserInput;
private void TextBox1_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
CheckUserInput = CheckUserInput + e.Text;
if (CheckUserInput.ElementAt(0).ToString() == "*" && e.Text != "*")
{
e.Handled = false;
}
else if (CheckUserInput.ElementAt(0).ToString() == "*")
{
PrefixValidated = true;
e.Handled = true;
}
else
{
e.Handled = true;
}
}
Thanks to Dark Templar for helping with the discovery of this solution. Using PreviewTextInput and validating the character only if there are no other characters in the textbox seems to give the correct result.
Setting e.Handled = true stops the character from actually entering the textbox even for a second so the user is never aware of the prefix.
Code:
private void UserInput_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
//if this is the first character entered, the textbox is not yet populated
//only perform validation if the character is a prefix
if (UserInput.Text != "")
return;
char CharAscii = (char)ScannerPrefix;
if (e.Text == CharAscii.ToString())
{
PrefixValidated = true;
e.Handled = true;
}
}
I have a textbox that accepts only numbers, no other characters. And I created the following function in the keypress method for that:
private void txtRGIE_KeyPress(object sender, KeyPressEventArgs e)
{
if (!Char.IsDigit(e.KeyChar) && e.KeyChar != (char)8)
{
e.Handled = true;
}
}
Validation is working when I type, I can't type special characters or letters like I wanted. However, if I copy a numeric string that contains dots or other characters and paste it into the field, it accepts normally. For example, if you copy: 323.323 / 323 and paste into the field, it will accept. How do I validate the characters I paste, allowing only numbers?
I have a textbox that accepts only numbers
And that's the flaw; saying "I have a knife here that i'm trying to use as a screwdriver, but i keep cutting myself with it, so i filed it smooth, but it's too big to get into the screw hole, so I filed it small, but it doesn't turn a + shaped screw very well, and the tip isn't hardened so it keeps breaking.."
The answer is to use a + shaped screwdriver, rather than keep repeatedly trying to kludge something not made for the job, into something that will do the job
A NumericUpDown control is the right tool for this job; it accepts only numbers, has configurable decimal places, and upper and lower limits, cannot have alphameric text typed or pasted into it and, bonus, the user can use the Up and Down cursor keys to change the value
NUD is a drop in replacement for your textbox, it's free and it's part of the standard lib so there isn't anything to install - just remember to get the .Value, not the .Text, and that it's a decimal, so you might want to cast it to something else to use it (double? int?) depending on what your app expects
If you don't like the little up down buttons, see here
you can use :
private void txtRGIE_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) &&
(e.KeyChar != '.'))
{
e.Handled = true;
}
// only allow one decimal point
if ((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.') > -1))
{
e.Handled = true;
}
}
or you can use a NumericUpDown instead
refer to this answers so you understand more.
You could use a MaskedTextBox instead of a regular one.
As already mentioned a NumericUpDown control is a good choice and to make it appear like a TextBox you can hide the up/down arrows e.g.
amountNumericUpDown1.Controls[0].Hide();
Or create a custom version with no up/down arrows and in this case no beep when pressing enter key.
public class SpecialNumericUpDown : NumericUpDown
{
public SpecialNumericUpDown()
{
Controls[0].Hide();
TextAlign = HorizontalAlignment.Right;
}
protected override void OnTextBoxResize(object source, EventArgs e)
{
Controls[1].Width = Width - 4;
}
public delegate void TriggerDelegate();
public event TriggerDelegate TriggerEvent;
protected override void OnKeyDown(KeyEventArgs e)
{
if (e.KeyCode == (Keys.Return))
{
e.Handled = true;
e.SuppressKeyPress = true;
TriggerEvent?.Invoke();
return;
}
base.OnKeyDown(e);
}
}
I have a problem that is haunting me for a while. I tried some solutions but they didn't worked.
I have a textbox that is for cash input ($999,99 for example). However I need to automatically input the "," and "." to display the value correctly.
I tried two solutions. One of them is this:
private void tx_ValorUnidade_TextChanged(object sender, EventArgs e)
{
string value = tx_ValorUnidade.Text.Replace(",", "").Replace("R$", "");
decimal ul;
//Check we are indeed handling a number
if (decimal.TryParse(value, out ul))
{
//Unsub the event so we don't enter a loop
tx_ValorUnidade.TextChanged -= tx_ValorUnidade_TextChanged;
//Format the text as currency
tx_ValorUnidade.Text = string.Format(System.Globalization.CultureInfo.CreateSpecificCulture("pt-BR"), "{0:C2}", ul);
tx_ValorUnidade.TextChanged += tx_ValorUnidade_TextChanged;
}
}
The result, however, is very weird.
The other one is this:
private void tx_ValorUnidade_KeyUp(object sender, KeyEventArgs e)
{
if (!string.IsNullOrEmpty(tx_ValorUnidade.Text))
{
System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo("en-US");
int valueBefore = Int32.Parse(tx_ValorUnidade.Text, System.Globalization.NumberStyles.AllowThousands);
tx_ValorUnidade.Text = String.Format(culture, "{0:N0}", valueBefore);
tx_ValorUnidade.Select(tx_ValorUnidade.Text.Length, 0); *
}
}
This one kinda works, but there is a issue: if the user wants to insert somethink like $10,00 it can't. It also crashes after 5 numbers.
For original reference, I got the 2 codes from other questions here.
How can I fix it? Am I using the examples wrong? Any thought is welcome.
I think you will be better off when formatting when the user moves to the next control, e.g. like below. Otherwise it will be very confusing as the text will change itself as the user is typing:
private void textBox1_Leave(object sender, EventArgs e)
{
Double value;
if (Double.TryParse(textBox1.Text, out value))
textBox1.Text = String.Format(System.Globalization.CultureInfo.CurrentCulture, "{0:C2}", value);
else
textBox1.Text = String.Empty;
}
Some people might want to actually format a textbox as they type. So this is my solution if anyone is looking for one.
It actually assumes you are entering one digit at a time so therefore as you press "1" it assumes "$0.01" and when they press "2" it then assumes "$0.12" and so on and so forth.
I could not find anything online about formatting as they typed. It has been tested and if any errors let me know.
private void textBox1_TextChanged(object sender, EventArgs e)
{
//Remove previous formatting, or the decimal check will fail including leading zeros
string value = textBox1.Text.Replace(",", "")
.Replace("$", "").Replace(".", "").TrimStart('0');
decimal ul;
//Check we are indeed handling a number
if (decimal.TryParse(value, out ul))
{
ul /= 100;
//Unsub the event so we don't enter a loop
textBox1.TextChanged -= textBox1_TextChanged;
//Format the text as currency
textBox1.Text = string.Format(CultureInfo.CreateSpecificCulture("en-US"), "{0:C2}", ul);
textBox1.TextChanged += textBox1_TextChanged;
textBox1.Select(textBox1.Text.Length, 0);
}
bool goodToGo = TextisValid(textBox1.Text);
enterButton.Enabled = goodToGo;
if (!goodToGo)
{
textBox1.Text = "$0.00";
textBox1.Select(textBox1.Text.Length, 0);
}
}
private bool TextisValid(string text)
{
Regex money = new Regex(#"^\$(\d{1,3}(\,\d{3})*|(\d+))(\.\d{2})?$");
return money.IsMatch(text);
}
To make it look nice I'd recommend starting the text box with the text $0.00 on the form load like so:
private void Form1_Load(object sender, EventArgs e)
{
textBox1.Text = "$0.00";
textBox1.SelectionStart = inputBox.Text.Length;
}
Just a slight modification to GreatNates answer.
private bool KeyEnteredIsValid(string key)
{
Regex regex;
regex = new Regex("[^0-9]+$"); //regex that matches disallowed text
return regex.IsMatch(key);
}
and insert this method into the textboxs preview input event like this.
private void TextBox1_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
e.Handled = KeyEnteredIsValid(e.Text);
}
That way you make sure that you can't make any mistakes when typing anything. You are limited to numbers only with my methods, while nates methods are formatting your string.
Cheers.
We can try following one as well.
txtCost.Text = String.Format("{0:c2}", myObj.Cost);
I struggled with this for hours too. I tried to use maskedTextBox but that was just clunky for the users to enter text. I also didn't like having to deal with the masking for calculations. I also looked into using the databinding formatting but that just seemed overkill.
The way I ended up going was not to use a TextBox for inputting numbers. Use the NumericUpDown object instead. No need conversion and you can set your decimals and thousands commas in the properties if you like ;) I set my increment to 1000 since i was dealing with income.
Do be aware that the .Text that comes through will have commas when there is a penny decimal and amount over 1000 (i.e. 1,000.01) , otherwise the decimal and trailing 0s are dropped.
I also found this short and sweet solution which worked well but was unneccesary with numericUpDown. You can put this on leave event.
Decimal val;
if (Decimal.TryParse(TxtCosPrice.Text, out val))
TxtCosPrice.Text = val.ToString("C");
else
MessageBox.Show("Oops! Bad input!");
This is my solution, it puts only dots, not money symbol. Hope can help somenone.
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
e.SuppressKeyPress = TextBox2Currency((TextBox)sender, e.KeyValue);
}
private bool TextBox2Currency(TextBox sender,int keyval)
{
if ((keyval >= 48 && keyval <= 58) || keyval == 46 || keyval == 8)
{
int pos = sender.SelectionStart;
int oriLen = sender.Text.Length;
string currTx = sender.Text.Replace(".", "").ToCurrency();
int modLen = currTx.Length;
if (modLen != oriLen)
pos += (modLen - oriLen);
sender.Text = currTx;
if ( pos>=0)
sender.SelectionStart = pos;
return false;
}
return true;
}
Here's my code:
private void Form1_Load(object sender, EventArgs e)
{
maskedTextBox1.Mask = "*[L]";
maskedTextBox1.MaskInputRejected += new MaskInputRejectedEventHandler(maskedTextBox1_MaskInputRejected);
}
How can I set it to accept only letters, but however many the user wants? Thanks!
This would be easy if masked text boxes accepted regular expression, but unfortunately they don't.
One (albeit not very pretty) way you could do it is to use the optional letter ? mask and put in the same amount as the maximum length you'll allow in the text box, i.e
maskedTextBox1.Mask = "????????????????????????????????.......";
Alternatively you could use your own validation instead of a mask and use a regular expression like so
void textbox1_Validating(object sender, CancelEventArgs e)
{
if (!System.Text.RegularExpressions.Regex.IsMatch(textbox1.Text, #"^[a-zA-Z]+$"))
{
MessageBox.Show("Please enter letters only");
}
}
Or yet another way would be to ignore any key presses other than those from letters by handling the KeyPress event, which in my opinion would be the best way to go.
private void textbox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), #"^[a-zA-Z]+$"))
e.Handled = true;
}
If you want only letters to be entered you can use this in keyPress event
if (!char.IsLetter(e.KeyChar) && !char.IsControl(e.KeyChar)) //The latter is for enabling control keys like CTRL and backspace
{
e.Handled = true;
}
I want to create separate textbox for numbers and string using c# code. I should not use jquery or javascript. Can anyone pls help me.
Condition:
Numeric Textbox: It should not allow characters, special characters.
String Textbox: Should not allow numbers, Special characters.
I think you can use Masked C# TextBox Control
Have a look at the Validation Controls ; these include client-side (javascript) and server-side validation logic.
for numbers only
private void txtType1_KeyPress(object sender, KeyPressEventArgs e)
{
int isNumber = 0;
e.Handled = !int.TryParse(e.KeyChar.ToString(), out isNumber);
}
for text only
private void txtType1_KeyPress(object sender, KeyPressEventArgs e)
{
int Length=textbox1.Length;
int Loop;
for(Loop=1;Loop<=Length;Loop++)
{
char c=textbox1.subString(Loop,1);
if(( c<'a' && c>'z') || (c<'A' && c>'Z'))
{
Messagebox.Show("Please Enter Only Alphabets");
e.Handle=true;
}
}
}