I wish to validate this TextBox against negative values and characters (must be integer without decimal)
It works well for . but I am not able to understand why it accepts negative value and characters?
My code is :
private void txtLifeMonths_KeyPress(object sender, KeyPressEventArgs e)
{
if (!Char.IsDigit(e.KeyChar) && (e.KeyChar == '.') && (e.KeyChar >= 0) && (e.KeyChar != (char)Keys.Back))
e.Handled = true;
}
You need to replace the first && operator with || and also move it to the end of your if statement then it should works as you want. Like this:
private void txtLifeMonths_KeyPress(object sender, KeyPressEventArgs e)
{
if (!Char.IsDigit(e.KeyChar) && (e.KeyChar >= 0) && (e.KeyChar != (char)Keys.Back) || (e.KeyChar == '.'))
e.Handled = true;
}
Related
hello i wanna understand this code .. i just take it copy past to my work space
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if ((e.KeyChar > (char)Keys.D9 || e.KeyChar < (char)Keys.D0) && e.KeyChar != (char)Keys.Back && e.KeyChar != '.')
{
e.Handled = true;
}
//Edit: Alternative
if (!char.IsDigit(e.KeyChar) && e.KeyChar != (char)Keys.Back && e.KeyChar != '.')
{
e.Handled = true;
}
}
Simply speaking a key event is sent to a chain of event handlers. Whenever someone says "I've handled it", the chain stops. So, when the key press is outside the range of numbers and not backspace or decimal point, this code sets e.Handled to true and the chain stops. That means event handling stops and the key is not shown in the textbox.
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.
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.
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;
}
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)}";
}
}