Skip to main content

How do I make a textbox that only accepts numbers?

How do I make a textbox that only accepts numbers?



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;
    }
}


Or use this 


private void textBox1_TextChanged(object sender, EventArgs e)
    {
        if (System.Text.RegularExpressions.Regex.IsMatch("[^0-9]", textBox1.Text))
        {
            MessageBox.Show("Please enter only numbers.");
            textBox1.Text.Remove(textBox1.Text.Length - 1);
        }
    }

Comments

Popular posts from this blog

MIME Types list

Multipurpose Internet Mail Extensions (MIME) is an Internet standard that extends the format of email to support: Text in character sets other than ASCII Non-text attachments: audio, video, images, application programs etc. Message bodies with multiple parts Header information in non-ASCII character sets    MIME Types list   Suffixes Mime .3dm x-world/x-3dmf .3dmf x-world/x-3dmf .a application/octet-stream .aab application/x-authorware-bin .aam application/x-authorware-map .aas application/x-authorware-seg .abc text/vnd.abc .acgi text/html .afl video/animaflex .ai application/postscript .aif audio/aiff .aif audio/x-aiff .aifc audio/aiff .aifc audio/x-aiff .aiff audio/aiff .aiff audio/x-aiff .aim application/x-aim .aip text/x-audiosoft-intra .ani application/x-navi-animation .aos application/x-nokia-9000-communicator-add-on-software .aps application/mime .arc ap...

What is the difference between ExecuteScalar, ExecuteReader and ExecuteNonQuery?

 ExecuteScalar is typically used when your query returns a single value. If it returns more, then the result is the first column of the first row. An example might be SELECT @@IDENTITY AS 'Identity'.  ExecuteReader is used for any result set with multiple rows/columns (e.g., SELECT col1, col2 from sometable).  ExecuteNonQuery is typically used for SQL statements without results (e.g., UPDATE, INSERT, etc.).