Validating the integer - c#

I want a Decimal Point in an Integer. If decimal Point is not there it shows Error Message.
Sir, The following code is written in User Control Text Box.The maximum Length given by the user When he access the user control.
The following code is restricts the user to enter the Decimal point after the maximum length.
Please the run the code Sir,
public virtual int MaximumLength { get; set; }
private void txtCurrency_KeyPress(object sender, KeyPressEventArgs e)
{
txtCurrency.MaxLength = MaximumLength + 3;
int dotIndex = txtCurrency.Text.IndexOf('.');
if (e.KeyChar != (char)Keys.Back)
{
if (char.IsDigit(e.KeyChar))
{
if (dotIndex != -1 && dotIndex < txtCurrency.SelectionStart && txtCurrency.Text.Substring(dotIndex + 1).Length >= 2)
{
e.Handled = true;
}
else if (txtCurrency.Text.Length == MaximumLength)
{
if (e.KeyChar != '.')
{ e.Handled = true; }
}
}
else
{
e.Handled = e.KeyChar != '.' || dotIndex != -1 || txtCurrency.Text.Length == 0 || txtCurrency.SelectionStart + 2 < txtCurrency.Text.Length;
}
}`enter code here`

decimal myValue = 12.4m;
int value = 0;
if (myValue - Math.Round(myValue) != 0)
{
throw new Exception("Has a decimal point");
}
else
{
value = (int)myValue;
}

You can use the RegularExpressions
private void textBox2_Validating(object sender, CancelEventArgs e)
{
Regex r = new Regex(#"^\d+.\d{0,1}$");
if (r.IsMatch(textBox2.Text))
{
MessageBox.Show("Okay");
}
else
{
e.Cancel = true;
MessageBox.Show("Error");
}
}
UPDATE:
private void textBox2_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar)
&& !char.IsDigit(e.KeyChar)
&& e.KeyChar != '.')
e.Handled = true;
if (e.KeyChar == '.'
&& (textBox2).Text.IndexOf('.') > -1) //Allow one decimal point
e.Handled = true;
}

Related

Restrict Textbox to 1 decimal place. Winform C#

I am developing a winform application using c# I have successfully implemented a way to restrict textbox to two decimal places. How can I do it to one decimal place. ?
My code for two decimal places.\
private void txtHraRep_KeyPress(object sender, KeyPressEventArgs e)
{
if (char.IsNumber(e.KeyChar) || e.KeyChar == '.')
{
if (Regex.IsMatch(
txtHraRep.Text,
"^\\d*\\.\\d{2}$")) e.Handled = true;
}
else e.Handled = e.KeyChar != (char)Keys.Back;
}
Changing to "^\d*\.\d{1}$")) e.Handled = true;
output
You can do this without regex by just checking where the decimal separator is in your text and then making sure that is 2 less than the length of the string (1 decimal place and 1 less for array length)
var decSeparator = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;
var idx = txtBasic.Text.IndexOf(decSeparator);
if(idx + 2 >= txtBasic.Text.Length)
...
Instead of using a TextBox control for the input, look at using a MaskedTextbox control for your input. This will alleviate any self validation of the input and can show the users what input can be expected of them with messages as to why their input was not correct.
More information about the MaskedTextbox control:
MaskedTextbox
MaskedTextbox.Mask property
MSDN Walkthrough: Working with the MaskedTextBox Control
I just tried
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
{
if (char.IsNumber(e.KeyChar) || e.KeyChar == '.')
{
if (Regex.IsMatch(
textBox1.Text,
"^\\d*\\.\\d{1}$")) e.Handled = true;
}
else e.Handled = e.KeyChar != (char)Keys.Back;
}
}
and it worked as it should. It restricted the input to one digit after the decimal point.
But you could enter more than one decimal point and then also more digits.
So you can either try
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (char.IsNumber(e.KeyChar) || ((e.KeyChar == '.') && (textBox1.Text.IndexOf('.')== -1 )))
{
if (Regex.IsMatch(
textBox1.Text,
"^\\d*\\.\\d{1}$")) e.Handled = true;
}
else e.Handled = e.KeyChar != (char)Keys.Back;
}
or something like
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (char.IsNumber(e.KeyChar) || ((e.KeyChar == '.') && (textBox1.Text.IndexOf('.')== -1 )))
{
if (textBox1.Text.IndexOf('.') > 0)
{
if (textBox1.Text.IndexOf('.') < textBox1.Text.Length - 1)
e.Handled = true;
}
}
else e.Handled = e.KeyChar != (char)Keys.Back;
}
Create A new TextBox that inherit TextBox like
[DefaultBindingProperty("Text")]
[DefaultProperty("Text")]
[DefaultEvent("ValueChanged")]
public class SpecializedTextBox : TextBox
{
private bool _allowNegativeSign = false;
public bool AllowNegativeSign
{
get { return _allowNegativeSign; }
set { _allowNegativeSign = value; }
}
public decimal? DecimalValue
{
get
{
decimal k;
if (decimal.TryParse(this.Text, out k))
return k;
else
return null;
}
set
{
if (value.HasValue)
this.Text = value.Value.ToString();
else
this.Text = "";
}
}
private void This_TextChanged(object sender, EventArgs e)
{
string s = base.Text;
int cursorpos = base.SelectionStart;
bool separatorfound = false;
for (int i = 0; i < s.Length; )
{
if (char.IsNumber(s[i]))
i++;
else if (AllowNegativeSign && i < System.Globalization.CultureInfo.CurrentUICulture.NumberFormat.NegativeSign.Length && s.StartsWith(System.Globalization.CultureInfo.CurrentUICulture.NumberFormat.NegativeSign))
i++;
else if (!separatorfound && s[i].ToString() == System.Threading.Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator)
{
separatorfound = true;
i++;
}
else
{
s = s.Remove(i, 1);
if (i < cursorpos)
cursorpos--;
}
}
if (base.Text != s)
{
base.Text = s;
base.SelectionStart = cursorpos;
base.SelectionLength = 0;
}
if (ValueChanged != null)
ValueChanged(this, EventArgs.Empty);
}
public event EventHandler ValueChanged;
private void InitializeComponent()
{
this.SuspendLayout();
//
// SpecializedTextBox
//
this.TextChanged += new System.EventHandler(this.This_TextChanged);
this.ResumeLayout(false);
}
public SpecializedTextBox()
: base()
{
InitializeComponent();
}
}
now use this text box and use DecimalValue to set or get your value
try:
List<string> doubleList = new List<string>(new string[]
{
"12345",
"1234.5",
"123.45",
"12.345",
"1.2345",
"1.2",
"1.23",
"1.234",
"1.23.45",
"12.3",
"123.4",
}) { };
private void button1_Click(object sender, EventArgs e)
{
foreach (var x in doubleList)
{
int countNumber = Regex.Matches(x, #"[0-9]").Count;
int countOfDot = Regex.Matches(x, #"\.").Count;
if (countOfDot == 1 && countNumber != 0) //contains "." and any digit
{
Console.WriteLine(x);
}
else if (countOfDot == 0 && countNumber != 0) //not contains "." and any digit
{
Console.WriteLine(x);
}
else
{
//do nothing . . .
}
}
}
output:
all except for **1.23.45** (2dots)

When I redo using this undo/redo code, the first thing undone cannot be redone

I am using the following code in order to implement undo/redo into my application:
public struct UndoSection
{
public string Undo;
public int Index;
}
--
public UndoSection(int index, string undo)
{
Index = index;
Undo = undo;
}
--
Stack<UndoSection> UndoStack = new Stack<UndoSection>();
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Modifiers == Keys.None && e.KeyCode == Keys.Delete)
UndoStack.Push(new UndoSection(richTextBoxPrintCtrl1.SelectionStart, richTextBoxPrintCtrl1.SelectedText));
else if (e.Control && e.KeyCode == Keys.Z)
{
e.Handled = true;
undo_Click(richTextBoxPrintCtrl1, new EventArgs());
}
}
public string[] RTBRedoUndo;
public int StackCount = 0;
public int OldLength = 0;
public int ChangeToSave = 5;
public bool IsRedoUndo = false;
--
public void RTBTextChanged()
{
if (richTextBoxPrintCtrl1.TextLength - OldLength >= ChangeToSave | richTextBoxPrintCtrl1.TextLength - OldLength <= ChangeToSave)
{
StackCount += 1;
RTBRedoUndo[StackCount] = richTextBoxPrintCtrl1.Text;
}
}
public void UndoCode()
{
IsRedoUndo = true;
if (StackCount > 0 && RTBRedoUndo[StackCount - 1] != null)
{
StackCount = StackCount - 1;
richTextBoxPrintCtrl1.Text = RTBRedoUndo[StackCount];
}
}
public void RedoCode()
{
if (IsRedoUndo == false && richTextBoxPrintCtrl1.Text.Substring(richTextBoxPrintCtrl1.Text.Length - 1, 1) == " ")
IsRedoUndo = true;
if (StackCount > 0 && RTBRedoUndo[StackCount + 1] != null)
{
StackCount = StackCount + 1;
richTextBoxPrintCtrl1.Text = RTBRedoUndo[StackCount];
}
However, if I type some text in my rich text box such as: "Hello. This is my application.", It will only let me redo up to "my". It won't let me redo "application.". And if I undo all text, I then cannot redo and restore the text.
What is causing this to behave in this manner? I really need to get this undo/redo code working correct. Could somebody help point me in the right direction, please?
--EDIT--
Redo code:
public void RedoCode()
{
if (IsRedoUndo == false && richTextBoxPrintCtrl1.Text.Substring(richTextBoxPrintCtrl1.Text.Length - 1, 1) == " ")
IsRedoUndo = true;
if (StackCount > 0 && RTBRedoUndo[StackCount + 1] != null)
{
StackCount = StackCount + 1;
richTextBoxPrintCtrl1.Text = RTBRedoUndo[StackCount];
}
}
It is called by a button click, using RedoCode();
Can you show how to call the Redo function?
as from what I can see you've missed out the below code
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Modifiers == Keys.None && e.KeyCode == Keys.Delete)
UndoStack.Push(new UndoSection(richTextBoxPrintCtrl1.SelectionStart, richTextBoxPrintCtrl1.SelectedText));
else if (e.Control && e.KeyCode == Keys.Z)
{
e.Handled = true;
undo_Click(richTextBoxPrintCtrl1, new EventArgs());
}
else if (e.Control && e.KeyCode == Keys.Y)
{
e.Handled = true;
redo_Click(richTextBoxPrintCtrl1, new EventArgs());
}

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

How to accept only one decimal point in a textbox?

The textbox will only accept numbers and only one decimal point.
For example the textbox contains "12345.56". When the period is pressed a second time on the keyboard it must not appear in the textbox because the textbox already contains a period.
[0-9]+(\.[0-9][0-9]?)?
Go with regular expressions.
hande KeyPress event and assuming its windows
void richTextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == '.' )
{
if (richTextBox1.Text.Contains('.'))
e.Handled = true;
}
}
**//Only numeric with Two decimal place comes in textbox and if user want to enter decimal again or space it will not allowed.**
if ((e.Key >= Key.D0 && e.Key <= Key.D9 ||
e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9 || e.Key == Key.Decimal || e.Key == Key.OemPeriod))
{
string strkey = e.Key.ToString().Substring(e.Key.ToString().Length - 1, e.Key.ToString().Length - (e.Key.ToString().Length - 1));
if (e.Key >= Key.D0 && e.Key <= Key.D9 ||
e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9)
{
TextBox tb = sender as TextBox;
int cursorPosLeft = tb.SelectionStart;
int cursorPosRight = tb.SelectionStart + tb.SelectionLength;
string result1 = tb.Text.Substring(0, cursorPosLeft) + strkey + tb.Text.Substring(cursorPosRight);
string[] parts = result1.Split('.');
if (parts.Length > 1)
{
if (parts[1].Length > 2 || parts.Length > 2)
{
e.Handled = true;
}
}
}
if (((TextBox)sender).Text.Contains(".") && e.Key == Key.Decimal)
{
e.Handled = true;
}
}
else
{
e.Handled = true;
}
if (e.Key >= Key.A && e.Key <= Key.Z ||
e.Key == Key.Space)
{
e.Handled = true;
}
if (Keyboard.Modifiers == ModifierKeys.Shift && e.Key == Key.OemPeriod)
{
e.Handled = true;
}
private bool isValueEnteredExceed100(string textBoxValue, string inputText)
{
var countPeriod = textBoxValue.Count(x => x.ToString().Equals("."));
if (countPeriod <= 1)
{
bool isValidNumber = AreAllValidNumericChars(inputText);
if (isValidNumber == true || inputText == ".")
{
double enterdValue;
bool returnValue = false;
if (textBoxValue != string.Empty || textBoxValue != "")
{
enterdValue = Convert.ToDouble(textBoxValue);
if (enterdValue > 0 && enterdValue <= 100)
{
returnValue = true;
}
}
return returnValue;
}
else
{
return isValidNumber;
}
}
else
{
return false;
}
}
private void AcceptedFromTextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
string textBoxValue = AcceptedFromTextBox.Text + e.Text;
if (textBoxValue == ".")
{
textBoxValue = "0" + e.Text;
AcceptedFromTextBox.Text = textBoxValue;
}
e.Handled = !isValueEnteredExceed100(textBoxValue, e.Text);
AcceptedFromTextBox.SelectionStart = AcceptedFromTextBox.Text.Length;
}
private bool AreAllValidNumericChars(string str)
{
Regex regex = new Regex(#"[0-9]$");
return regex.IsMatch(str);
}
Another example ,
private void txtPrice_KeyPress(object sender, KeyPressEventArgs e)
{
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;
}
}
Code on Keypress event of textbox
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;
}

Categories

Resources