Click here to Skip to main content
15,889,335 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hello all pro
i want a methods that create caller textbox a only numeric textbox
what is that?????????
help me please??
like :
i have this in my form load and it takes textbox4 a only numeric one
textbox4.applyonlydigits();
Posted

Hi Try this below code

C#
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
                //You may make it 4 or 5 depends on your application
                if (textBox1.Text.IndexOf(' ') == textBox1.Text.Length - 2)
                    e.Handled = true;
        }
 
Share this answer
 
v3
This is the code for a numeric only textbox

C#
private void textBox4_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;
    }
}


But better create a custom control by adding a class and inherit textbox
and override its OnKeyPress Event

C#
using System.Windows.Forms;

namespace Test
{
    public partial class NumericTextBox : TextBox
    {
        protected override void OnKeyPress(KeyPressEventArgs e)
        {
            base.OnKeyPress(e);
            if (!char.IsControl(e.KeyChar)
                && !char.IsDigit(e.KeyChar)
                && e.KeyChar != '.')
            {
                e.Handled = true;
            }

            // only allow one decimal point
            if (e.KeyChar == '.'
                && (this as TextBox).Text.IndexOf('.') > -1)
            {
                e.Handled = true;
            }
        }
    }
}

you will get a new control on your toolbox
 
Share this answer
 
Comments
daghune 29-Aug-12 0:53am    
Thank you very much , it really help me

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900