Numeric TextBox In C#
How to add a seprate Text Box That allows only Numeric Values.
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
AlanPosted Oct 13, 2008, 2:03 PM
I'd check out both the MaskedTextBox and the NumericUpDown controls to see if they'll do what you want :
http://msdn.microsoft.com/en-us/library/system.windows.forms.maskedtextbox.aspx
http://msdn.microsoft.com/en-us/library/system.windows.forms.numericupdown.aspx
Also, if you want to restrict the input of a standard TextBox (including characters pasted in) to integers, then here's some code I wrote recently to do this (set the MaxLength property to whatever you want first):
private bool reentry = false;
private void textBox1_TextChanged(object sender, EventArgs e) chars = new List(textBox1.Text);
{
if (reentry)
{
reentry = false;
return;
}
if (textBox1.Text.Length == 0) return;
int index = textBox1.SelectionStart;
int removals = 0;
List
for (int i = chars.Count - 1; i >= 0; i--)
{
if (chars[i] < 48 || chars[i] > 57)
{
chars.RemoveAt(i);
removals++;
}
}
if (chars.Count == 0)
{
reentry = true;
textBox1.Text = "";
reentry = false;
return;
}
if (removals > 0)
{
reentry = true;
textBox1.Text = new string(chars.ToArray());
reentry = false;
}
int len = textBox1.Text.Length;
if (chars[0] == '0' && chars.Count > 1)
{
reentry = true;
textBox1.Text = textBox1.Text.TrimStart('0');
reentry = false;
int len2 = textBox1.Text.Length;
if (len2 == 0)
{
reentry = true;
textBox1.Text = "0";
reentry = false;
len2 = 1;
}
removals += len - len2;
}
if (removals == 0) return;
textBox1.SelectionStart = Math.Min(Math.Max(index - removals, 0), textBox1.Text.Length + 1);
}