Limit Numbers after Decimal on Key Press Event - c#

I am using the following code to take only digits from user and only one decimal point , that is working fine for me on KeyPress Event :
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
{
e.Handled = true;
}
if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1)
{
e.Handled = true;
}
Now I want to Limit the numbers/Digits after the decimal/dot i.e 35.25468, means it take only 6 numbers/digits after the dot/decimal.
Update me !

private void price_tb_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;
}
if (!char.IsControl(e.KeyChar))
{
TextBox textBox = (TextBox)sender;
if (textBox.Text.IndexOf('.') > -1 &&
textBox.Text.Substring(textBox.Text.IndexOf('.')).Length >= 3)
{
e.Handled = true;
}
}
}
This code will help you. It takes only one decimal place and two digit after one decimal place and you can change it accordingly.

you can add an additional check like this
TextBox textBox = (TextBox) sender;
if (textBox.Text.IndexOf('.') > -1 &&
textBox.Text.Substring(textBox.Text.IndexOf('.')).Length >=3)
{
e.Handled = true;
}
Note, the Substring will include the '.' and hence the check is >=3.

On the keypress event, and or validate event, count the number of chars after decimal point. On key press, suppress it. on validate, remove extra decimal places. Make sure you're getting the decimal point char from NumberFormatInfo, not all cultures use '.', ie. in France, their decimal point is actually a comma

On keypress, format the string and set the textBox.Text to the formatted string.
TextBox.Text = String.Format("{0:N3"}", textBox.Text)
This particular format cuts off the number at the 3rd decimal.

I had textBox.SelectionLength == 0 to allow the modification of selected text:
private void price_tb_KeyPress(object sender, KeyPressEventArgs e) {
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.') {
e.Handled = true;
}
TextBox textBox = (TextBox)sender;
// only allow one decimal point
if (e.KeyChar == '.' && textBox.Text.IndexOf('.') > -1) {
e.Handled = true;
}
if (!char.IsControl(e.KeyChar) && textBox.SelectionLength == 0) {
if (textBox.Text.IndexOf('.') > -1 && textBox.Text.Substring(textBox.Text.IndexOf('.')).Length >= 3) {
e.Handled = true;
}
}
}

The issue I have with the answer of Both FM is that you cannot edit the text when you have entered a decimal place and two decimals.
This code also takes a minus amount.
private void TextBoxAmount_KeyPress(object sender, KeyPressEventArgs e)
{
if (char.IsDigit(e.KeyChar))
{
// OK, but not more than 2 after the [.]
if (((TextBox)sender).Text.Contains('.'))
{
if (((TextBox)sender).Text.IndexOf('.') + 2 < ((TextBox)sender).Text.Length)
{
if (((TextBox)sender).SelectionStart > ((TextBox)sender).Text.IndexOf('.'))
{
e.Handled = true;
}
}
}
}
else if (char.IsControl(e.KeyChar))
{
// Always OK
}
else if (e.KeyChar == '.' && !((TextBox)sender).Text.Contains('.'))
{
// First [.] == OK
}
else if (e.KeyChar == '-' && !((TextBox)sender).Text.Contains('-'))
{
// First [-] == OK
}
else
{
e.Handled = true;
}
}
private void TextBoxAmount_KeyUp(object sender, KeyEventArgs e)
{
if (((TextBox)sender).Text.Contains('-'))
{
((TextBox)sender).Text = $"-{((TextBox)sender).Text.Replace("-", string.empty)}";
}
}

Related

How to disallow zero in textbox using char.IsDigit

I have the below code wherein it works for only numbers and backspace but I want to also have that no zeros are allowed, but it is not working
private void TxtNumber4_KeyPress(object sender, KeyPressEventArgs e)
{
if ((char.IsDigit(e.KeyChar)) || (char.IsControl(e.KeyChar)) || (int)e.KeyChar == 0)
{
errorProvider1.SetError(LblNum2, "");
LblNum2.Text = "";
}
else
{
e.Handled = true;
errorProvider1.SetError(LblNum2, "Allow Only Numeric Values !");
LblNum2.Text = "Allow Only Numeric Values !";
}
}
Let's start from the other end, i.e. what we allow: '1'..'9' (note they are chars, say '1' is not int 1) and all the control chars:
private void TxtNumber4_KeyPress(object sender, KeyPressEventArgs e) {
// If e.KeyChar is a control character
// or it some char from '1'..'9' we allow it
if (char.IsControl(e.KeyChar) || e.KeyChar >= '1' && e.KeyChar <= '9') {
LblNum2.Text = "";
}
else {
e.Handled = true;
LblNum2.Text = "Allow Only Numeric Values !";
}
// Let's not repeat ourselves
errorProvider1.SetError(LblNum2, LblNum2.Text);
}

Restrict Dot( . ) in Datagridview Cell at start of the Cell

I am developing an Point of Sale application in C# dot Net which contains a datagridview.
I want to restrict some cells value of datagridview to following thing.
Do not enter a Dot(".") at the beginning of the cell (This is really needed).
Do not enter any alphabet or any other character. (I have developed this but needed an improved idea)
Only Enter Numerical values with negative numbers too. (I have developed this but needed an improved idea)
Guide my in this case.
Following is my Code
private void Numeric_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.' && e.KeyChar != 46)
//if (!char.IsDigit(e.KeyChar) && e.KeyChar != '.')
{
e.Handled = true;
}
// only allow one decimal point
if ((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.') > -1) && ((sender as TextBox).Text.IndexOf('.') != 1))
{
e.Handled = true;
}
}
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
e.Control.KeyPress -= new KeyPressEventHandler(Numeric_KeyPress);
if (dataGridView1.CurrentCell.ColumnIndex == 1)
{
TextBox tb = e.Control as TextBox;
if (tb != null)
{
tb.KeyPress += new KeyPressEventHandler(Numeric_KeyPress);
}
}
}
The easiest way is to handle the CurrentCellDirtyStateChanged event.
I'm using a regular expression to validate the value. This code allows you to enter only numbers including negative.
private void DataGridView_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
var cell = dataGridView.CurrentCell;
if (cell.ColumnIndex != 1)
return;
string value = cell.EditedFormattedValue.ToString();
string pattern = #"^-$ | ^-?0$ | ^-?0\.\d*$ | ^-?[1-9]\d*\.?\d*$";
if (Regex.IsMatch(value, pattern, RegexOptions.IgnorePatternWhitespace))
{
dataGridView.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
else
{
dataGridView.CancelEdit();
}
}
Note: this code will not allow users to enter numbers in their own culture.

How make certain datagridview column to only accept numeric value in C#

The following code makes DataGridView Column4 to only accept numeric value and one decimal dot . and it works fine for example it accepts values such as (4.50 , 3.00 , 13.60)
But the problem is: I still can save a decimal dot by itself inside the cell (Without any numbers just the decimal dot) and I do not want the cell to have only decimal dot because the sql database (money column) do not accept only decimal dot.
Any one knows how to prevent the cells in Column4 to not accept only decimal dot but to accept values like: (4.50 , 3.00 , 13.60) ?
please help Thank you
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
e.Control.KeyPress -= new KeyPressEventHandler(AnyColumnKeyPress);
if (dataGridView1.CurrentCell.ColumnIndex == 4 ) //Desired Column
{
TextBox tb = e.Control as TextBox;
if (tb != null)
{
tb.KeyPress += new KeyPressEventHandler(AnyColumnKeyPress);
}
}
}
private void AnyColumnKeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
{
e.Handled = true;
}
// allow 1 dot:
if ((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.') > -1))
{
e.Handled = true;
}
}
Change your function to be:
private void AnyColumnKeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
{
e.Handled = true;
}
// allow 1 dot:
if ((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.') > -1))
{
if ( (sender as TextBox).Text != "." ) {
e.Handled = true;
}
}
}
checked the code above and i could still enter a dot char, altered it slightly to be more readable to me.
if (!(char.IsControl(e.KeyChar) || char.IsDigit(e.KeyChar)) || e.KeyChar == '.')
{
e.Handled = true;
}
Tested and I could enter only digits.

TextBox with Numeric Input

I am working on a database application and using this class to validate numeric numbers on KeyPress event of TextBox.
The numbers may have (-) negative values with fixed decimal places (third parameter dPlaces) e.g. 10000, -1000, 12345.45, -12345.45
After adding a decimal, I am not able to edit other digits although without a decimal it is working perfectly.
Thanks in advance
public static class Util
{
public static void NumInput(object sender, KeyPressEventArgs e, int dPlaces)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.' && (e.KeyChar != '-'))
{
e.Handled = true;
}
// only allow one decimal point
if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1)
{
e.Handled = true;
}
var a = (sender as TextBox).SelectionLength;
// only allow minus sign at the beginning
var x = (sender as TextBox).Text.IndexOf('-');
if (e.KeyChar == '-' && (sender as TextBox).Text.IndexOf('-') > 0)
{
e.Handled = true;
}
if (!char.IsControl(e.KeyChar))
{
TextBox textBox = (TextBox)sender;
if (textBox.Text.IndexOf('.') > -1 &&
textBox.Text.Substring(textBox.Text.IndexOf('.')).Length >= dPlaces + 1)
{
e.Handled = true;
}
}
}
}
Its because of Logical operation in your IF BLOCK for comparing length =3 and char = '.'.
Change that last part of your code with : (EDIT : To handle the issue of inserting text before '.')
if (!char.IsControl(e.KeyChar))
{
TextBox textBox = (TextBox)sender;
// get position of new char to be inserted
int position = textBox.SelectionStart;
if (textBox.Text.IndexOf('.') > -1 && position > textBox.Text.IndexOf('.')) // check location of new char
if(!(textBox.Text.Substring(textBox.Text.IndexOf('.')).Length <= dPlaces + 1))
{
e.Handled = true;
}
}
This will do your job..!!!
EDIT : Also Do the following to STOP Copy/Past in textbox
textbox.ShortcutsEnabled = false;

textbox validation for allow one " . " value c#

I want textbox validation for allowing only one . value and only numbers. Means my textbox value should take only numerics and one . value. Value should be like 123.50.
I am using a code for adding .oo or .50 value at end of my value.
My code is
double x;
double.TryParse(tb.Text, out x);
tb.Text = x.ToString(".00");
It is taking all the keys from keyboard, but I want to take only numbers and one . value.
Add a Control.KeyPress event handler for your textbox.
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar)) //bypass control keys
{
int dotIndex = textBox1.Text.IndexOf('.');
if (char.IsDigit(e.KeyChar)) //ensure it's a digit
{ //we cannot accept another digit if
if (dotIndex != -1 && //there is already a dot and
//dot is to the left from the cursor position and
dotIndex < textBox1.SelectionStart &&
//there're already 2 symbols to the right from the dot
textBox1.Text.Substring(dotIndex + 1).Length >= 2)
{
e.Handled = true;
}
}
else //we cannot accept this char if
e.Handled = e.KeyChar != '.' || //it's not a dot or
//there is already a dot in the text or
dotIndex != -1 ||
//text is empty or
textBox1.Text.Length == 0 ||
//there are more than 2 symbols from cursor position
//to the end of the text
textBox1.SelectionStart + 2 < textBox1.Text.Length;
}
}
You may do it through designer or in your constructor like this:
public Form1()
{
InitializeComponent();
//..other initialization
textBox1.KeyPress += new KeyPressEventHandler(textBox1_KeyPress);
}
I have also added several checks to ensure, that you could insert digits not only in the end of the text, but in any position. Same with a dot. It controls that you have not more than 2 digits to the right from the dot. I've used TextBox.SelectionStart Property to get the position of the cursor in the textbox. Check this thread for more info about that: How do I find the position of a cursor in a text box?
Simplly in keyPress event of your textBox you could do this ...
e.Handled = !char.IsDigit(e.KeyChar)&&(e.KeyChar != '.') && !char.IsControl(e.KeyChar);
if ((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.') > -1))
{
e.Handled = true;
}
try this one
private void textBox1_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 == '.'
&& textBox1.Text.IndexOf('.') > -1)
e.Handled = true;
}
try this code and just replace what you want input type 'validinpu' string.
try
{
short charCode = (short)Strings.Asc(e.KeyChar);
string validinput = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-0123456789 .";
if (Strings.InStr(validamt, Conversions.ToString(Strings.Chr(charCode)), Microsoft.VisualBasic.CompareMethod.Binary) == 0)
{
charCode = 0;
}
if (charCode == 0)
{
e.Handled = true;
}
}
Another example ,
private void txtPrice_KeyPress(object sender, KeyPressEventArgs e)
{
// To disallow typing in the beginning writing
if (txtPrice.Text.Length == 0)
{
if (e.KeyChar == '.')
{
e.Handled = true;
}
}
if (!char.IsDigit(e.KeyChar) && e.KeyChar != 8 && e.KeyChar != 46)
{
e.Handled = true;
}
if (e.KeyChar == '.' && txtPrice.Text.IndexOf('.') > -1)
{
e.Handled = true;
}
}
Also try this short one
e.Handled = (!(e.KeyChar == (char)Keys.Back || e.KeyChar == '.')); //allow dot and Backspace
e.Handled = (e.KeyChar == '.' && TextBox1.Text.Contains(".")); //allow only one dot
this example only allow one dot and backspace
if (textBox.Text!="")
{
string txt = textBox.Text;
if (e.KeyChar.ToString().Any(Char.IsNumber) || e.KeyChar == '.')
{
textBox.Text = rate;
}
else
{
MessageBox.Show("Number Only", "Warning");
textBox.Text = "";
}
}
My tested code
if(e.KeyChar.Equals('\b'))
{
e.Handled = false;
}
else
if (!char.IsControl(e.KeyChar)
&& !char.IsDigit(e.KeyChar)
&& e.KeyChar != '.')
{
e.Handled = true;
}
else
// only allow one decimal point
if (e.KeyChar == '.'
&& textBox1.Text.IndexOf('.') > -1)
{
e.Handled = true;
}

Categories

Resources