Introduction
I needed one textbox that accepts a number and uses separated character on each three numbers as right.
I searched for this on The Code Project, but couldn't find any such article. So I decided to create this one.
Notice: Numeric TextBox is not MasktextBox, this textBox is dynamic but masktextbox is static. When you changing a number, the position of the separated character changes.
Using the Code
Add numericTextBox in your project, then drag and drop on the form.
Numeric Textbox contains these properties:
MaxValue: With this property, you could enter max of a number as per your requirement.
Invalidsound: In this property, you could set invalid sound for when the user presses the wrong key, e.g. when pressing a letter character.
SeparatedChar: A separated character is a character that is placed between numbers. Default of separated character is ",".
Value: The value of a numeric textbox that you see has Int64 type. When you want to use Int32 type, use this:
(Int32)numericTextBox.Value
How It Works
NumericTextBox is a textbox that manages the keyPressed event:
protected override void OnKeyPress(KeyPressEventArgs e)
{
isKeyPress = true;
base.OnKeyPress(e);
double val = (this.Text.Length == 0 ? 0 :
double.Parse(this.Text.Replace(sepratedChar.ToString(), "")));
if (Char.IsDigit(e.KeyChar) && val * 10 +
int.Parse(e.KeyChar.ToString()) <= maxValue)
{
}
else if (e.KeyChar == '\b')
{
}
else if ((ModifierKeys & (Keys.Control | Keys.Alt)) != 0)
{
}
else if (this.SelectionLength > 0)
{
}
else
{
e.handle = true;
}
Then when text is changed, call SetSepratedChar procedure, in SetSepratedChar while Value>1000, divide by 1000 and insert SeparatedChar but it's different between digits and Del Key and backspace button, because selectionstart is a different position.
private void SetSepratedChar(int index)
{
isKeyPress = false;
isDelKeyPress = false;
Int64 intValue = Value;
int selectionStart = this.SelectionStart;
this.Clear();
while (intValue >= 1000)
{
Int64 mod = intValue % 1000;
if (mod == 0)
this.Text = this.Text.Insert(0, sepratedChar.ToString() + "000");
else if (mod.ToString().Length == 1)this.Text =
this.Text.Insert(0, sepratedChar.ToString() + "00" + mod.ToString());
else if (mod.ToString().Length == 2)
this.Text = this.Text.Insert(0,
sepratedChar.ToString() + "0" + mod.ToString());
else
this.Text = this.Text.Insert(0,
sepratedChar.ToString() + mod.ToString());
intValue = intValue / 1000;
}
this.Text = this.Text.Insert(0, intValue.ToString());
this.SelectionStart = selectionStart + index;
}
I needed an integer number, but if you think this component is useful for decimal numbers, please let me know.
Please give me some tips.