Prevent continue Typing in TextBox When a Char is Entered - c#

I have a textbox which user should type a price in it.
I need to prevent continue typing if price starts with 0.
For example user can not type "000" or "00009".
I tried this on KeyPress, but nothing!
if (txt.Text.StartsWith("0"))
return; Or e.Handeled = true;

try this:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
//only allow digit and (.) and backspace
if ((e.KeyChar < '0' || e.KeyChar > '9') && e.KeyChar != '\b' && e.KeyChar != '.')
{
e.Handled = true;
}
var txt = sender as TextBox;
//only allow one dot
if (txt.Text.Contains('.') && e.KeyChar == (int)'.')
{
e.Handled = true;
}
//if 0, only allow 0.xxxx
if (txt.Text.StartsWith("0")
&& !txt.Text.StartsWith("0.")
&& e.KeyChar != '\b'
&& e.KeyChar != (int)'.')
{
e.Handled = true;
}
}

You could use the TextChanged-event for this.
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (this.textBox1.Text == "0") this.textBox1.Text = "";
}
This will only work, if the TextBox is empty on startup.

I solved it Myself:
private void txtPrice_KeyPress(object sender, KeyPressEventArgs e)
{
if (txtPrice.Text.StartsWith("0") && !char.IsControl(e.KeyChar))
{
e.Handled = true;
return;
}
}

Related

keypress event for number in WinForm TextBox in C#

I want to limit user to type just numbers in TextBox.
I add this code In keypress Event:
private void txtPartID_KeyPress(object sender, KeyPressEventArgs e)
{
if (((e.KeyChar >= '0') && (e.KeyChar <= '9')) == false)
{
e.Handled = true;
}
}
but after that BackSpace key don't work for this TextBox. How can I change this?
You can check for backspace using this,
if(e.KeyChar == '\b')
And better way to check only for numbers is
private void txtPartID_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = !(Char.IsNumber(e.KeyChar) || e.KeyChar == 8);
}
private void TxtBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!(Char.IsDigit(e.KeyChar) && (e.KeyChar == (char)Keys.Back)))
e.Handled = true;
}
I think you should handle both back key and delete key.
if (!(Char.IsDigit(e.KeyChar) && (e.KeyChar == (char)Keys.Back)&& (e.KeyChar == (char)Keys.Delete)))
e.Handled = true;
You can use it
private void txtColumn_KeyPress(object sender, KeyPressEventArgs e)
{
if (((e.KeyChar >= '0') && (e.KeyChar <= '9') || (e.KeyChar == (char)Keys.Back)) == false)
{
e.Handled = true;
}
}

How to enter space bar in textbox that accepts only character?

if (!Char.IsControl(e.KeyChar) && !char.IsLetter(e.KeyChar))
{
e.Handled = true;
base.OnKeyPress(e);
(for example Jonh space Jambo) but it work only johnjambo
Just add one more condition and it should work.
&& !char.IsWhiteSpace(e.KeyChar)
Your overall code should look like this
if (!char.IsControl(e.KeyChar) && !char.IsLetter(e.KeyChar) && !char.IsWhiteSpace(e.KeyChar))
{
e.Handled = true;
base.OnKeyPress(e);
}
Add the check for IsWhiteSpace too to the keypress()
e.keychar can be converted in Keys object like this:
private void textBox_KeyPress_Event(object sender, KeyPressEventArgs e)
{
if (char.IsLetter(e.KeyChar) || (Keys)e.KeyChar == Keys.Space)
e.Handled = true;
}
if (!(Char.IsLetter(e.KeyChar) || (e.KeyChar == (char)Keys.Back) || Char.IsWhiteSpace(e.KeyChar)))
e.Handled = true;

allow textbox to support numbers and OemMinus only?

In my code I use this piece of code to validate textbox to support only, but I want to allow OemMinus (-) also how can I do this?
private void card_No_KeyDown(object sender, KeyEventArgs e)
{
nonNumberEntered = false;
// Determine whether the keystroke is a number from the top of the keyboard.
if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
{
// Determine whether the keystroke is a number from the keypad.
if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9 &&
e.KeyCode == Keys.Oemplus)
{
// Determine whether the keystroke is a backspace.
if (e.KeyCode != Keys.Back)
{
// A non-numerical keystroke was pressed.
// Set the flag to true and evaluate in KeyPress event.
nonNumberEntered = true;
}
}
}
}
private void card_No_KeyPress(object sender, KeyPressEventArgs e)
{
if (nonNumberEntered == true)
{
MessageBox.Show("not allowed");
e.Handled = true;
}
}
You could handle the KeyPress event like this
private void card_No_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsNumber(e.KeyChar) && e.KeyChar != '-' && e.KeyChar != (char)Keys.Back)
e.Handled = true;
}
But that won't prevent the user from copy pasting an invalid value so you can also handle the TextChanged event.
private void card_No_TextChanged(object sender, EventArgs e)
{
if (!String.IsNullOrEmpty(card_No.Text))
{
if (Regex.Matches(card_No.Text, #"(-|\d)").Count != card_No.Text.Length)
{
//pasted an invalid value
MessageBox.Show("Invalid value entered");
}
}
}
private void card_No_KeyPress(object sender, KeyPressEventArgs e)
{
var textBox = sender as TextBox;
//handels integers, decimal numbers and OemMinus (-) character
if (((!char.IsControl(e.KeyChar))
&& (!char.IsDigit(e.KeyChar))
&& (e.KeyChar != '-')
) || (textBox != null
&& (e.KeyChar != '.'
&& (textBox.Text.IndexOf('.') > -1))))
e.Handled = true;
if (e.Handled)
MessageBox.Show(#"not allowed");
}
//prevent copy and past and delete pasted text
private void card_No_TextChanged(object sender, EventArgs e)
{
if (card_No.Text.Length >0)
{
if (Regex.Matches(card_No.Text, #"(-|\d)").Count != card_No.Text.Length)
{
if (!Clipboard.ContainsText()) return;
var txt = Clipboard.GetText();
if (card_No.Text.Contains(txt))
{
int ind = card_No.Text.IndexOf(txt, System.StringComparison.Ordinal);
var text = card_No.Text.Substring(0, ind);
card_No.Text = text;
MessageBox.Show(#"not allowed");
}
else if (txt.Contains(card_No.Text))
{
int ind = txt.IndexOf(card_No.Text, System.StringComparison.Ordinal);
var text = txt.Substring(0, ind);
card_No.Text = text;
MessageBox.Show(#"not allowed");
}
}
}
}

Make a specific column only accept numeric value in datagridview in Keypress event

I need to make datagridview that only accept the numeric value for specific column only in keypress event. Is there any best way to do this?
Add an event of EditingControlShowing
In EditingControlShowing, check that if the current cell lies in the desired column.
Register a new event of KeyPress in EditingControlShowing(if above condition is true).
Remove any KeyPress event added previously in EditingControlShowing.
In KeyPress event, check that if key is not digit then cancel the input.
Example:
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
e.Control.KeyPress -= new KeyPressEventHandler(Column1_KeyPress);
if (dataGridView1.CurrentCell.ColumnIndex == 0) //Desired Column
{
TextBox tb = e.Control as TextBox;
if (tb != null)
{
tb.KeyPress += new KeyPressEventHandler(Column1_KeyPress);
}
}
}
private void Column1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
}
You must use DataGridView.CellValidating Event like this :
private void dataGridView1_CellValidating(object sender,
DataGridViewCellValidatingEventArgs e)
{
if (e.ColumnIndex == 1) // 1 should be your column index
{
int i;
if (!int.TryParse(Convert.ToString(e.FormattedValue), out i))
{
e.Cancel = true;
label1.Text ="please enter numeric";
}
else
{
// the input is numeric
}
}
}
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
e.Control.KeyPress -= new KeyPressEventHandler(Column1_KeyPress);
if (dataGridView1.CurrentCell.ColumnIndex == 4) //Desired Column
{
TextBox tb = e.Control as TextBox;
if (tb != null)
{
tb.KeyPress += new KeyPressEventHandler(Column1_KeyPress);
}
}
}
private void Column1_KeyPress(object sender, KeyPressEventArgs e)
{
// allowed only numeric value ex.10
//if (!char.IsControl(e.KeyChar)
// && !char.IsDigit(e.KeyChar))
//{
// e.Handled = true;
//}
// allowed numeric and one dot ex. 10.23
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;
}
}
The answer given is excellent unless you require decimal places as others have pointed out.
In this event you need to extend the validation, add the using and vars below to get a culture variable value for the decimal separator
using System.Globalization;
NumberFormatInfo nfi = Thread.CurrentThread.CurrentCulture.NumberFormat;
char decSeperator;
decSeperator = nfi.CurrencyDecimalSeparator[0];
Extend the validation to:
if (!char.IsControl(e.KeyChar) && !(char.IsDigit(e.KeyChar)
| e.KeyChar == decSeperator))
{
e.Handled = true;
}
// only allow one decimal point
if (e.KeyChar == decSeperator
&& (sender as TextBox).Text.IndexOf(decSeperator) > -1)
{
e.Handled = true;
}
Private WithEvents txtNumeric As New DataGridViewTextBoxEditingControl
Private Sub DataGridView1_EditingControlShowing(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles DataGridView1.EditingControlShowing
txtNumeric = CType(e.Control, DataGridViewTextBoxEditingControl)
End Sub
Private Sub txtNumeric_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtNumeric.KeyPress
If (DataGridView1.CurrentCell.ColumnIndex > 0) Then
If (Not Char.IsControl(e.KeyChar) And Not Char.IsDigit(e.KeyChar) And Not e.KeyChar = ".") Then
e.Handled = True
Else
'only allow one decimal point
If (e.KeyChar = "." And txtNumeric.Text.Contains(".")) Then
e.Handled = True
End If
End If
End If
End Sub
You could also try this way, with accept decimals character
private void Column1_KeyPress(object sender, KeyPressEventArgs e)
{
//allow number, backspace and dot
if (!(char.IsDigit(e.KeyChar) || e.KeyChar == (char)Keys.Back || e.KeyChar == '.'))
{
e.Handled = true;
}
//allow only one dot
if (e.KeyChar == '.' && (sender as TextBox).Text.Contains("."))
{
e.Handled = true;
}
}
I was doing a matrix calculator and was using two DataGridView objects. Here's a code that worked for me. I took the very first comment from this post and changed it a bit.
//Adding characters to a cell
private void dataGridView_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (e.Control != null)
{
e.Control.KeyPress += new KeyPressEventHandler(Column1_KeyPress);
Console.WriteLine(e.Control.Text);
}
}
//Handling presses for minus dot and numbers
private void Column1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '-' && e.KeyChar != '.')
e.Handled = true;
if (e.KeyChar == '.')
{
if (((DataGridViewTextBoxEditingControl)sender).Text.Length == 0)
e.Handled = true;
if (((DataGridViewTextBoxEditingControl)sender).Text.Contains('.'))
e.Handled = true;
}
if (e.KeyChar == '-')
{
if (((DataGridViewTextBoxEditingControl)sender).Text.Length != 0)
e.Handled = true;
if (((DataGridViewTextBoxEditingControl)sender).Text.Contains('-'))
e.Handled = true;
}
}

Textbox with decimal input improvement

I have a textbox that gets a decimal value say 10500.00 the problem is that the way I have it, when you enter a value and then enter the decimals it would not allow you to backspace or clear the textbox to input a new value.. it just gets stuck.. I have tried to set the value back to 0.00 but i think i placed it on the wrong place because it wont change it. Here is my code
private void txtTransferAmount_KeyPress(object sender, KeyPressEventArgs e)
{
bool matchString = Regex.IsMatch(textBoxTransfer.Text.ToString(), #"\.\d\d");
if (matchString)
{
e.Handled = true;
}
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;
}
}
What type of change do you suggest so that I may be able to backspace or clear the texbox an enter a new value?.
You can trap for the Backspace (BS) char (8) and, if found, set your handle to false.
Your code may look like this...
....
// only allow one decimal point
if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1)
{
e.Handled = true;
}
if (e.KeyChar == (char)8)
e.Handled = false;
A suggestion to make your code a bit more intuitive to interpret what your event handler is doing, you may want to create a var that implies the logic you are implementing. Something like...
private void txtTransferAmount_KeyPress(object sender, KeyPressEventArgs e)
{
bool ignoreKeyPress = false;
bool matchString = Regex.IsMatch(textBoxTransfer.Text.ToString(), #"\.\d\d");
if (e.KeyChar == '\b') // Always allow a Backspace
ignoreKeyPress = false;
else if (matchString)
ignoreKeyPress = true;
else if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
ignoreKeyPress = true;
else if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1)
ignoreKeyPress = true;
e.Handled = ignoreKeyPress;
}
Easiest way would be :
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.' && e.KeyChar != '\b')
{
e.Handled = true;
}

Categories