Validation-Textboxes allowing only decimals - c#

I am using following code for validating textbox.
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = SingleDecimal(sender, e.KeyChar);
}
public bool SingleDecimal(System.Object sender, char eChar)
{
string chkstr = "0123456789.";
if (chkstr.IndexOf(eChar) > -1 || eChar == Constants.vbBack)
{
if (eChar == ".")
{
if (((TextBox)sender).Text.IndexOf(eChar) > -1)
{
return true;
}
else
{
return false;
}
}
return false;
}
else
{
return true;
}
}
Problem is Constants.vbBack is showing error.If i didnt use Constants.vbBack,backspace is not workimg.What alteration can i make to work backspace.Can anybody help?

here is the code I would use...
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
// allows 0-9, backspace, and decimal
if (((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8 && e.KeyChar != 46))
{
e.Handled = true;
return;
}
// checks to make sure only 1 decimal is allowed
if (e.KeyChar == 46)
{
if ((sender as TextBox).Text.IndexOf(e.KeyChar) != -1)
e.Handled = true;
}
}

You can make a method to check if it's a number.
Instead of checking for the . as a decimal separator you should get it from CurrentCulture object as it could be another character depending on where in the world you are.
public bool isNumber(char ch, string text)
{
bool res = true;
char decimalChar = Convert.ToChar(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator);
//check if it´s a decimal separator and if doesn´t already have one in the text string
if (ch == decimalChar && text.IndexOf(decimalChar) != -1)
{
res = false;
return res;
}
//check if it´s a digit, decimal separator and backspace
if (!Char.IsDigit(ch) && ch != decimalChar && ch != (char)Keys.Back)
res = false;
return res;
}
Then you can call the method in the KeyPress event of the TextBox:
private void TextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if(!isNumber(e.KeyChar,TextBox1.Text))
e.Handled=true;
}

create a component inherited from textbox and use this code:
protected override void OnKeyPress(KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
{
e.Handled = true;
}
// only allow one decimal point
if (e.KeyChar == '.' && Text.IndexOf('.') > -1)
{
e.Handled = true;
}
base.OnKeyPress(e);
}

Here is a Vb.Net version for #Eclipsed4utoo's answer
If (((Asc(e.KeyChar) < 48 Or Asc(e.KeyChar) > 57) And Asc(e.KeyChar) <> 8 And Asc(e.KeyChar) <> 46)) Then
e.Handled = True
Exit Sub
End If
' checks to make sure only 1 decimal is allowed
If (Asc(e.KeyChar) = 46) Then
If (sender.Text.IndexOf(e.KeyChar) <> -1) Then
e.Handled = True
End If
End If

This codes for decimals. If you want to use float also, you just use double insteat int
And it will be delete automaticaly last wrong charachters
private void txt_miktar_TextChanged(object sender, TextChangedEventArgs e)
{
if ((sender as TextBox).Text.Length < 1)
{
return;
}
try
{
int adet = Convert.ToInt32((sender as TextBox).Text);
}
catch
{
string s = "";
s = (sender as TextBox).Text;
s = s.Substring(0, s.Length - 1);
(sender as TextBox).Text = s;
(sender as TextBox).Select(s.Length, s.Length);
}
}

How about using the example from MSDN?
Are u using the '.' as decimal seperator? if so than I don't know why you are using
if (((TextBox)sender).Text.IndexOf(eChar) > -1)

Here some code from my app. It handle one more case as will related to selection
protected override void OnKeyPress(KeyPressEventArgs e)
{
if (e.KeyChar == '\b')
return;
string newStr;
if (SelectionLength > 0)
newStr = Text.Remove(SelectionStart, SelectionLength);
newStr = Text.Insert(SelectionStart, new string(e.KeyChar, 1));
double v;
//I used regular expression but you can use following.
e.Handled = !double.TryParse(newStr,out v);
base.OnKeyPress(e);
}
here regex expression if like to use them instead of that easy type parsing
const string SIGNED_FLOAT_KEY_REGX = #"^[+-]?[0-9]*(\.[0-9]*)?([Ee][+-]?[0-9]*)?$";
const string SIGNED_INTEGER_KEY_REGX = #"^[+-]?[0-9]*$";
const string SIGNED_FLOAT_REGX = #"^[+-]?[0-9]*(\.[0-9]+)?([Ee][+-]?[0-9]+)?$";
const string SIGNED_INTEGER_REGX = #"^[+-]?[0-9]+$";

I believe this is the perfect solution as it not only confines the text to numbers, only a leading minus sign, and only one decimal point, but it allows the replacement of selected text if it contains a decimal point. The selected text still cannot be replaced by a decimal point if there is a decimal point in the non-selected text. It allows a minus sign only if it's the first character or if the entire text is selected.
private bool DecimalOnly_KeyPress(TextBox txt, bool numeric, KeyPressEventArgs e)
{
if (numeric)
{
// only allow numbers
if (!char.IsDigit(e.KeyChar) && e.KeyChar != Convert.ToChar(Keys.Back))
return true;
}
else
{
// allow a minus sign if it's the first character or the entire text is selected
if (e.KeyChar == '-' && (txt.Text == "" || txt.SelectedText == txt.Text))
return false;
// if a decimal point is entered and if one is not already in the string
if ((e.KeyChar == '.') && (txt.Text.IndexOf('.') > -1))
{
if (txt.SelectedText.IndexOf('.') > -1)
// allow a decimal point if the selected text contains a decimal point, that is the
// decimal point replaces the selected text
return false;
else
// don't allow a decimal point if one is already in the string and the selected text
// doesn't contain one
return true;
}
// if the entry is not a digit
if (!Char.IsDigit(e.KeyChar))
{
// if it's not a decimal point and it's not a backspace then disallow
if ((e.KeyChar != '.') && (e.KeyChar != Convert.ToChar(Keys.Back)))
{
return true;
}
}
}
// allow only a minus sign but only in the beginning, only one decimal point, any digit, a
// backspace, and replace selected text.
return false;
}

Here is a vb.net version that allows negative decimal figure, prevent copy and paste while making sure the negative sign is not in the middle of the text or the decimal point not at the beginning of the text
Public Sub Numeric(textControl As Object, e As KeyPressEventArgs)
Dim Index As Int32 = textControl.SelectionStart
Dim currentLine As Int32 = textControl.GetLineFromCharIndex(Index)
Dim currentColumn As Int32 = Index - textControl.GetFirstCharIndexFromLine(currentLine)
Dim FullStop As Char
FullStop = "."
Dim Neg As Char
Neg = "-"
' if the '.' key was pressed see if there already is a '.' in the string
' if so, dont handle the keypress
If e.KeyChar = FullStop And textControl.Text.IndexOf(FullStop) <> -1 Then
e.Handled = True
Return
End If
'If the '.' is at the begining of the figures, prevent it
If e.KeyChar = FullStop And currentColumn <= 0 Then
e.Handled = True
Return
End If
' if the '-' key was pressed see if there already is a '-' in the string
' if so, dont handle the keypress
If e.KeyChar = Neg And textControl.Text.IndexOf(Neg) <> -1 Then
e.Handled = True
Return
End If
'If the '-' is in the middle of the figures, prevent it
If e.KeyChar = Neg And currentColumn > 0 Then
e.Handled = True
Return
End If
' If the key aint a digit
If Not Char.IsDigit(e.KeyChar) Then
' verify whether special keys were pressed
' (i.e. all allowed non digit keys - in this example
' only space and the '.' are validated)
If (e.KeyChar <> Neg) And (e.KeyChar <> FullStop) And (e.KeyChar <> Convert.ToChar(Keys.Back)) Then
' if its a non-allowed key, dont handle the keypress
e.Handled = True
Return
End If
End If
End Sub
Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox1.KeyPress
Numeric(sender, e)
End Sub

try this with asp:RegularExpressionValidator controller
<asp:RegularExpressionValidator ID="rgx"
ValidationExpression="[0-9]*\.?[0-9][0-9]" ControlToValidate="YourTextBox" runat="server" ForeColor="Red" ErrorMessage="Decimals only!!" Display="Dynamic" ValidationGroup="lnkSave"></asp:RegularExpressionValidator>

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

Making first letter of a textbox upper case

I'm having trouble with this code. I want it to make the first letter of the Textbox upper case, but if the textbox is empty the program crashes. I know the problem is to do with the length of the substring, so if anyone can help me fix this it would be great!
NB: The name of the textbox is richTextBoxGuess and this code runs every time the text in the textbox changes.
if (char.IsLower(Convert.ToChar(richTextBoxGuess.Text.Substring(0, 1))) ) // Checks if first letter is lower case
{
richTextBoxGuess.Text = richTextBoxGuess.Text.Replace(richTextBoxGuess.Text.Substring(0, 1), richTextBoxGuess.Text.ToUpper()); // Changes first letter to uppercase
richTextBoxGuess.SelectionStart = 2; // Puts cursor after first letter
}
This will not destroy the previous formatting of the content:
private void richTextBoxGuess _TextChanged(object sender, EventArgs e)
{
if (richTextBoxGuess .Text.Length <= 0) return;
string s = richTextBoxGuess.Text.Substring(0, 1);
if (s != s.ToUpper())
{
int curSelStart = richTextBoxGuess.SelectionStart;
int curSelLength = richTextBoxGuess.SelectionLength;
richTextBoxGuess.SelectionStart = 0;
richTextBoxGuess.SelectionLength = 1;
richTextBoxGuess.SelectedText = s.ToUpper();
richTextBoxGuess.SelectionStart = curSelStart;
richTextBoxGuess.SelectionLength = curSelLength;
}
}
Note that it doesn't not keep track of the changes and will not restore them when you keep adding at the front..
If you need culture invariance use the CultureInfo.CurrentCulture parameter of ToUpper()!
Check if the richTextBoxGuess is null or empty
if( richTextBoxGuess != ""){ // or different from null
if (char.IsLower(Convert.ToChar(richTextBoxGuess.Text.Substring(0, 1))) ){
//your code
}
}
Write this extension method:
public static string CapitalizeFirstLetter(this string input)
{
if (string.IsNullOrEmpty(input))
{
return input;
}
return input.Substring(0, 1).ToUpper(CultureInfo.CurrentCulture) + input.Substring(1);
}
And then use it as
richTextBoxGuess.Text = richTextBoxGuess.Text.CapitalizeFirstLetter();
private void _capitalizeFirstWord(Object sender, KeyPressEventArgs e)
{
if (_richTB.Text.Trim() == String.Empty)
{
e.KeyChar = char.ToUpper(e.KeyChar);
}
}
If you want to capitalize every word
char _pre,_cur;
_pre=' ';
private void _capitalizeEveryWord(Object sender, KeyPressEventArgs e)
{
_cur = e.KeyChar;
if (_richTB.Text.Trim() == String.Empty)
{
e.KeyChar = char.ToUpper(e.KeyChar);
}
e.Handled = !(char.IsLetter(e.KeyChar) || e.KeyChar == (char)Keys.Back || e.KeyChar == ' ' && (!(_cur == _pre)) || e.KeyChar == '.' && (!(_pre == _cur)));
_pre=_cur
}

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

Limit Numbers after Decimal on Key Press Event

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

Categories

Resources