accept only num and dot when press - c#

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.

Related

Why TextBox validation doesn't work

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;
}

How to accept just certain characters into a textbox?

How do I limit textbox from accepting letter A,B,C,D only? I've tried this code, but it still accepts letters aside from letters A,B,C,D.
e.Handled = !char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar);
I agree with the comment that if all you want is a single character that actually using a combo box may be more appropriate, but if you're planning on allowing the user to enter a series of the limited characters then it may be worth having a look at an article that I wrote a few years ago about how to restrict the characters that are allowed in the text box, which is available at "Restrict characters entered into textbox".
Further to DanDan78's comment below the important code is;
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
Dim allowedChars As String = "0123456789"
If allowedChars.IndexOf(e.KeyChar) = -1 Then
' Invalid Character
e.Handled = True
End If
End Sub
On the KeyPress event of your TextBox, you can just use this simple code to achieve your aim:
if (e.KeyChar < 'A' || e.KeyChar > 'D')
e.Handled = true;
If you wish to accept lower and upper case A-D:
if ((e.KeyChar < 'A' || e.KeyChar > 'D') && (e.KeyChar <'a' || e.KeyChar > 'd'))
e.Handled = true;
If you also wish to allow 'special' characters like backspace, delete, etc., you need to also allow characters below ASCII code 32:
if ((e.KeyChar < 'A' || e.KeyChar > 'D') && (e.KeyChar <'a' || e.KeyChar > 'd') && e.KeyChar > 32)
e.Handled = true;
Following a further user comment, in order to allow A-D, a-d and backspace only, the following should suffice:
if ((e.KeyChar < 'A' || e.KeyChar > 'D') && (e.KeyChar <'a' || e.KeyChar > 'd') && e.KeyChar != 8)
e.Handled = true;
Attach a KeyPressEventHandler to the text box:
textBox.KeyPress += new KeyPressEventHandler(keyPressed);
Then create an event to handle these letters:
private void keyPressed(Object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 'A' || e.KeyChar == 'B' || e.KeyChar == 'C' || e.KeyChar == 'D')
{
e.Handled = true;
}
}
This will stop the text box accepting these letters

How to create a textbox that only accepts numbers and one that only accepts letters in WPF?

I would just like to know how to create a textbox that only allows the user to type numbers, one that allows numbers and a fullstops and one that only allows the user to type letters?
I used this code for Windows Form:
private void YearText_KeyPress(object sender, KeyPressEventArgs e) //Textbox only accepts numbers
{
char ch = e.KeyChar;
if (!Char.IsDigit(ch) && ch != 8 && ch != 13)
{
e.Handled = true;
}
}
private void NameText_KeyPress(object sender, KeyPressEventArgs e) //Textbox only accepts letters
{
if (!char.IsLetter(e.KeyChar) && !char.IsControl(e.KeyChar) && !char.IsWhiteSpace(e.KeyChar))
e.Handled = true;
}
private void ResellPriceText_KeyPress(object sender, KeyPressEventArgs e) //Textbox that allows only numbers and fullstops
{
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;
}
}
But I soon found out this can't be done with WPF. I'm not fussed about things such as the ability to paste letters/numbers.
This can be done in WPF, in fact you can even do it with very similar event handler based code, however, don't this - it is a terrible user experience. This will prevent users from copying and pasting when they accidentally include surrounding spaces and will prevent entering scientific numbers e.g. 100e3.
Instead use validations (on the trimmed input) and prevent the user from continuing if the validations fail.

declare textbox key press event code at some other place and call it?

i need to handle keypress event of my textboxes so that the user enters only numeric data in the textboxes, i have my code which is working fine and im posting it below, but my concern is that, i have more than 30 textboxes with the same requirement and i dont want to write the same code for the key press events of the 30 textboxes, but i cannot write this code in a method and call that method..is there any way i can solve this issue so that i can wrilte the code at one place and call it in al the key press events of the textboxes or any other way which makes my code look standard and reduce the lines, im posting my code below
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;
}
Sure, you can use one event handler for all text boxes
TextBox tb = new TextBox();
tb.KeyPress += tb_KeyPress;
TextBox tb2 = new TextBox();
tb2.KeyPress += tb_KeyPress;
void 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;
}
}

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