Numeric TextBox In C#
How to add a seprate Text Box That allows only Numeric Values.
1 Answer
Know the answer? Post it. Somebody with the same question will find it here.
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
AlanRank #669 · 3.6K reputationPosted Oct 13, 2008, 10:03 AM EDT
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);
}