I'm programming a game. I want to accept only a one or two digit number.
Only digits 0-9 allowed.
Only 1 or 2 digits allowed.
When second digit entered, number is accepted. Program goes to range check (Message to user if number is odd or greater than 20)
For one digit number, user has to indicate done by pressing return.
Here is what I have:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
char ch = e.KeyChar;
if (ch == 46 && textBox1.Text.IndexOf('.') != -1)
{
e.Handled = true;
return;
}
if (!char.IsDigit(ch) && ch != 8 && ch != 46)
// 8 = Backspace, 46 = decimal point
{
e.Handled = true; // Exits without taking any further action
}
}
{
char ch = e.KeyChar;
if (ch == 46 && textBox1.Text.IndexOf('.') != -1)
{
e.Handled = true;
return;
}
if (!char.IsDigit(ch) && ch != 8 && ch != 46)
// 8 = Backspace, 46 = decimal point
{
e.Handled = true; // Exits without taking any further action
}
}

Sumit JoshiRank #1,252 · 1.4K reputationPosted Aug 12, 2015, 10:11 PM EDT
Prem Anandh JRank #8,962 · 213 reputationPosted Aug 13, 2015, 8:34 PM EDT
-> Set TextBox max length to 2
{
private void TextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!(char.IsNumber(e.KeyChar)) && !(e.KeyChar == '\b'))
{
e.Handled = true;
}
else
{
e.Handled = false;
}
}
Rajeesh MenothRank #118 · 18.4K reputationPosted Aug 13, 2015, 8:41 PM EDT
"Value1" Columns="2" MaxLength="2" Text="1" runat="server"/>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 == '.') && ((sender as TextBox).Text.IndexOf('.') > -1)) { e.Handled = true; } }