Hello again,

I'm trying to create a text field that only accepts numbers, a single decimal, and a dash (for negatives) but only as the first character.

I have conquered everything except for pasting, and have no idea on where to begin. Below is the current code (working!) code that I have.

I know when it triggers paste, I want each character that it is trying to be pasted to be check for a set of conditions(it has to be a number, if it is a dash (negative sign) it must be pasted to be the first character space and be the only one. Further if there is a decimal it must check that there are no decimals currently in the text field or in front of it in the pasted string. If any character violates any of these rules it must be deleted.

Even if you can only figure out how to do a little of this (IE: How to interrupt to paste function - or how to change it before it is added) you have been a huge help, so don't be nervous about an incomplete answer!


Here is my working code:

private void textBox1_KeyPress(object sender, KeyPressEventArgs e) //important to note that this kind of event "KeyPress" Is nessecary for this kind of operation!
        {
            //My rather long numbers only textbox if statment

            if (!System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), "\\d+")
                // Allowing backspace
                && !(e.KeyChar == '\b')
                // Allowing decimals
                && !((e.KeyChar == '.' && textBox1.Text.IndexOf('.') == -1))
                /* The following is allowing negative signs ONLY if it is in the first space or all the text is selected otherwise it does not allow it! And the || is the OR statment*/
                && (!((e.KeyChar == '-') && (textBox1.Text.IndexOf('-') == -1) && (textBox1.SelectionStart == 0 || textBox1.SelectedText == textBox1.Text)))
                //End if bracket (below)
                )
            // if e.Handled = true; it does not allow the keystroke to be added! (and it's not linking to a function or anything complex like that too!)
            {
                e.Handled = true;
            }

        }

Recommended Answers

All 4 Replies

The simplest way i think would be

private void textBox1_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if(textBox1.Text!="")
                Convert.ToDouble(textBox1.Text);
            }
            catch
            {
                textBox1.Text = "";
            }

        }

Thanks - I think that will work.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.