Format a number in a Textbox on Enter key press - c#

In a windows Form, I have a text box where I put amounts, for example I would type 18369.25 then press Enter key, the textbox should be formatted to: 18 369,25
how to do that ?

Subscribe to the textbox's KeyPress event with an event handler similar to the one below:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == '\r')
{
decimal value;
if (decimal.TryParse(
textBox1.Text,
NumberStyles.Any,
CultureInfo.InvariantCulture,
out value))
{
textBox1.Text = value.ToString(
"### ### ##0.00",
CultureInfo.InvariantCulture).TrimStart().Replace(".", ",");
}
}
}

I did some expiriments, but none seemed to work. So I came out with this solution. I know its not the best one, but at least it work (for at least what you required):
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
string s = textBox1.Text;
if (s.Contains('.'))
{
string[] arr = s.Split('.');
decimal dec = decimal.Parse(arr[0]);
textBox1.Text = string.Format("{0},{1}", dec.ToString("## ###"), arr[1]);
}
}
}
If you have any other requirements, please let me know.
bye

Related

Ban enter letters textBox

How to prohibit the introduction of letters in textBox? That is, this construction works incorrectly
public void textBox1_KeyDown(object sender, KeyEventArgs e)
{
try
{
char s = Convert.ToChar(textBox1.Text);
if ((s <= '0') || (s >= '9'))
MessageBox.Show("You have entered a symbol! Please enter a number");
}
catch (System.FormatException)
{
MessageBox.Show("You have entered a symbol! Please enter a number");
}
}
You need to either check the key being entered in the KeyDown event (e.Key property) as the key value is added to the Text field after the event or use the TextChanged event - this would catch cut & paste operations as well.
public void textBox1_TextChanged(object sender, TextChangedEventArgs e)
{
if (!ValidNumericString(textBox1.Text))
{
MessageBox.Show("You have entered invalid characters! Please enter a number");
Dispatcher.BeginInvoke(new Action(() => textBox1.Undo()));
e.Handled = true;
}
}
public bool ValidNumericString(string IPString)
{
return IPString.All(char.IsDigit);
// OR make this check for thousands & decimals if required
}
You can use the OnKeyPress event which allows you to cancel the key event manually if you want to.
void textBox1_OnKeyPress(KeyPressEventArgs e)
{
e.Handled = true; // this won't send the key event to the textbox
}
If you want to accept only numbers and related chars (negative sign, decimal separators, ...), you can test the entered char :
void textBox1_OnKeyPress(KeyPressEventArgs e)
{
NumberFormatInfo numberFormatInfo = CultureInfo.CurrentCulture.NumberFormat;
string decimalSeparator = numberFormatInfo.NumberDecimalSeparator;
string groupSeparator = numberFormatInfo.NumberGroupSeparator;
string negativeSign = numberFormatInfo.NegativeSign;
string keyInput = e.KeyChar.ToString();
e.Handled = !(Char.IsDigit(e.KeyChar) || keyInput.Equals(negativeSign) || keyInput.Equals(decimalSeparator) || keyInput.Equals(groupSeparator));
}
This is untested code because I'm at work, but you get the idea.
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (Control.ModifierKeys == Keys.Control) return; // Check if ctrl is pressed
var key = (char) e.KeyValue; // ASCII to char
if (char.IsDigit(key) || char.IsControl(key) || char.IsWhiteSpace(key)) return; // Check if "key" is a number
MessageBox.Show("You have entered a symbol! Please enter a number");
textBox1.Text = textBox1.Text.Substring(0, textBox1.Text.Length - 1); // Remove last element
textBox1.SelectionStart = textBox1.Text.Length; // Return to initial position
}

unable to clear a textbox data

I'm not able to delete textbox data with the code below
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if(char.IsDigit(e.KeyChar)==false)
{
count++;
}
if (count == 1)
{
textBox1.Text = ("");
count = 0;
}
}
tried using clear method as well the alphabet i entered stays in the textbox and when i type any key it get overwritten but i want the textbox to be empty the second time and the prev data to be removed
you just need to say you've handled the event:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (char.IsDigit(e.KeyChar) == false)
{
count++;
}
if (count == 1)
{
textBox1.Text = ("");
count = 0;
e.Handled = true; // this bit fixes it
}
}
use textBox1.Text = ""; OR textBox1.clear();
This will clear your textbox.
You are doing it wrong. You can just paste in a bunch of letters with Ctrl+V. Delete the KeyDown event and create a TextChanged event. This code should accomplish what you are attempting. Please tell me if there is any more details and I will add to my answer.
private void textBox1_TextChanged(object sender, EventArgs e)
{
foreach (char c in textBox1.Text)
if (!char.IsDigit(c)) { textBox1.Clear(); break; }
}
Add this to your text box key press event your problem will be solved
e.handle = true;

Detect decimal separator

I have to detect decimal separator in current windows setting. Im using visual studio 2010, windows form. In particular, if DecimalSeparator is comma, if user input dot in textbox1, I need show zero in textbox2.
I tryed with this code, but not works:
private void tbxDaConvertire_KeyPress(object sender, KeyPressEventArgs e)
{
string uiSep = CultureInfo.CurrentUICulture.NumberFormat.NumberDecimalSeparator;
if (uiSep.Equals(","))
{
while (e.KeyChar == (char)46)
{
tbxConvertito.Text = "0";
}
}
}
I have tryed also this code, but not work:
private void tbxDaConvertire_KeyPress(object sender, KeyPressEventArgs e)
{
string uiSep = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;
if (uiSep.Equals(","))
{
if (e.KeyChar == (char)46)
{
tbxConvertito.Text = "0";
}
}
}
Solution:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
char a = Convert.ToChar(Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator);
if (e.KeyChar == a)
{
e.Handled = true;
textBox1.Text = "0";
}
}
That way, when you hit . or , you will have a 0 in your TextBox.
EDIT:
If you want to insert a 0 everytime you hit the decimal separator, this is the code:
char a = Convert.ToChar(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator);
if (e.KeyChar == a)
{
e.KeyChar = '0';
}
Actually you should be using
CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator
instead of
CultureInfo.CurrentUICulture.NumberFormat.NumberDecimalSeparator
Using the second one gives you the OS default settings, which might be different then user Regional Locales for particular user account logged to this PC.
Credits to berhir and Grimm for pointing out the [docs]
You shouldn't use a while loop, I think it will freeze the application, use if instead, the problem might be here

To Disable Negative Values Inside a TextBox

I m Working On A windows Form.. I Need my TextBox Not To Accept negative Values ..How Can I Do this..
IS There Any Property Availiable For Doing The same...
You need to write keypress event of textbox like :
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
}
You can also user numeric updown control to prevent negetive values.
UPDATE :
Ref: Sai Kalyan Akshinthala
My code will not handle the case of copy/paste. User can enter negative values by copy/paste. So I think Sai Kalyan Akshinthala's answer is correct for that case except one small change of Length >= 2.
private void textBox1_TextChanged(object sender, EventArgs e)
{
if(textBox1.Text.Length >= 2)
{
int acceptednumber = Convert.ToInt32(textBox1.Text);
if(acceptednumber < 0)
{
textBox1.Text = "";
MessageBox.Show("-ve values are not allowed");
}
else
{
textBox1.Text = textBox1.Text;
}
}
}
yes you can do write the following code part in textchanged event of textbox
if(textBox1.Text.Length >= 2)
{
int acceptednumber = Convert.ToInt32(textBox1.Text);
if(acceptednumber < 0)
{
textBox1.Text = "";
MessageBox.Show("-ve values are not allowed");
}
else
{
textBox1.Text = textBox1.Text;
}
}
just use min and pattern will not allow to enter a minus value
min="0" pattern="^[0-9]+$" in input type

textbox formatting

I need some help with my code.
I need the following format,
12345-1234567-1
Basically I want to type just digits and when text length reaches 5, it should append '-' and again on reaching to the length of 13, again it should append '-'.
My code is doing this fine. But when I use backspace/delete, it always append '-' to the 6th and 14th location.
Here is my code,
private void nicNo_txt_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode.ToString() != "Back" || e.KeyCode.ToString() != "Space" || e.KeyCode.ToString() != "Delete")
{
if (nicNo_txt.TextLength == 5 || nicNo_txt.TextLength == 13)
nicNo_txt.AppendText("-");
}
}
Regards
Have you tried MaskedTextBox, in it you can specify a mask in whatever format you need
One below will do
For formating after changes - replace format method with anything you like:
void oTextBoxAmount_TextChanged(object sender, EventArgs e)
{
//throw new NotImplementedException();
if (sender is TextBox)
{
TextBox tb = sender as TextBox;
tb.Text = FormatAmount(tb.Text);
tb.SelectionStart = tb.Text.Length;
}
}
For filtering keys (example below filters digits but you can change conditions):
void oTextBoxAmount_KeyPress(object sender, KeyPressEventArgs e)
{
int val = (int)e.KeyChar;
if (val >= 0x30 && val <= 0x39)
{
//Digits are ok
}
else if (val == 0x08)
{
//Backspace is ok
}
else
{
//Other are disallowed
e.Handled = true;
}
}
You can use AJAX Control Toolkit's Masked Edit. It does exactly what you want.
Ajax Control Toolkit - Masked Edit

Categories

Resources