I want to set my textbox to be able to only accept numeric values as well as a '.', I typed this code in

private void ipAddTextBox_KeyPress(object sender, KeyPressEventArgs e)
            int isNum = 0;

            if (e.KeyChar == ".")
                e.Handled = false;
            else if (!int.TryParse(e.KeyChar.ToString(), out  isNum))
                e.Handled = true;

but there's an error telling me that "The type or namespace name 'KeyPressEventArgs' could not be found"

anyone has any idea why this is happening and how i can solve this problem?


Recommended Answers

All 7 Replies

I'm assuming this is inside a form and you have using System.Windows.Forms at the top. I'd retype the line and see what it says.

Also, instead of that clumsy tryparse statement, use

else if (Char.IsNumber(e.KeyChar) == false) {

Do you mean at the top? I don't see a "using System.Windows.Forms", that means I don't have it? And is there supposed to be a KeyPress event in the Events panel beside the properties panel?

You need to include that so it knows where to find the KeyPressEventArgs class, so put the statement at the tope.

Yes, there should be a KeyPress event in the properties panel for the textbox. Make sure you are looking at the events (lightning bolt at top).

Oh, but when i include that statement, there'll be an error telling me that "The type or namespace name 'Forms' does not exist in the namespace 'System.Windows', and I don't see any keypress event in the events panel too.

Sorry I'm a beginner so any help will be appreciated. Thanks :)

It sounds like you have a console project that you are trying to force to be a forms application. Check the references for the project and see if System.Windows.Forms.dll is one of them. It should be automatically added by the IDE.

Which brings me to: Which (if any) IDE are you using to develop your project?

System.Windows.Forms is not one of the references for the project. I'm actually using Microsoft Visual Studio 2010 Express for Windows Phone.

This code has got to do, what you have asked in the 1st post of the thread:

public partial class Form1 : Form
        bool bJump;
        public Form1()

        private void textBox1_TextChanged(object sender, EventArgs e)
            if (!bJump)
                int intValue = 0;
                string strValue = textBox1.Text;
                bool bChecking = int.TryParse(strValue, out intValue);
                if (!bChecking && strValue != "")
                    strValue = strValue.Remove(strValue.Length - 1, 1);
                    bJump = true;
                textBox1.Text = strValue;
                textBox1.SelectionStart = textBox1.Text.Length;
                bJump = false;
Be a part of the DaniWeb community

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