Solved

entering numbers in c# .NET

Posted on 2009-05-14
5
385 Views
Last Modified: 2012-08-13
hi,
           I have one phone number text box.In that it takes numbers only.it is working fine.i takes only numbers. But Back Space is not working.I post my code
private void txtPhone_KeyPress(object sender, KeyPressEventArgs e)

        {

            int isNumber = 0;

            

            e.Handled = !int.TryParse(e.KeyChar.ToString(), out isNumber);
 

        }

Open in new window

0
Comment
Question by:mannevenu
5 Comments
 
LVL 13

Expert Comment

by:kaylanreilor
ID: 24392792
I think you should "specialize" your text box by using validators:
http://www.codeproject.com/KB/validation/validationprovider.aspx
You can use some masks and the System.Text.RegularExpressions.RegEx class like here: (search for RegEx)
http://www.cornetdesign.com/2008/01/tdd-of-winform-app-part-5-validating.html
See the MSDN doc here : http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.aspx

Let's have a look to the System.Text.RegularExpressions namespace and to the System.Windows.Forms.ErrorProvider provider class :
http://msdn.microsoft.com/en-us/library/system.windows.forms.errorprovider.aspx
There are some complete example.

Nevertheless, if you really wants to continu this way, e.KeyChar.ToString() is a string so you can use its Trim methods : http://msdn.microsoft.com/en-us/library/system.string_members.aspx
0
 
LVL 13

Expert Comment

by:kaylanreilor
ID: 24392805
So as I said Trim methods without any argument "Removes all leading and trailing white-space characters from the current String object" : http://msdn.microsoft.com/en-us/library/t97s7bs3.aspx
Probably I can write something like this:
e.Handled = !int.TryParse(e.KeyChar.ToString().Trim(), out isNumber);
 But I'm still convinced that you should develop something like the codeproject article shows above.
0
 
LVL 10

Accepted Solution

by:
Marcjev earned 500 total points
ID: 24392929
Or use something like this validation in a derived textbox or your implementation.
You should only handle your allowed characters though...
public class NumericTextBox : TextBox

{

    bool allowSpace = false;
 

    // Restricts the entry of characters to digits (including hex), the negative sign,

    // the decimal point, and editing keystrokes (backspace).

    protected override void OnKeyPress(KeyPressEventArgs e)

    {

        base.OnKeyPress(e);
 

        NumberFormatInfo numberFormatInfo = System.Globalization.CultureInfo.CurrentCulture.NumberFormat;

        string decimalSeparator = numberFormatInfo.NumberDecimalSeparator;

        string groupSeparator = numberFormatInfo.NumberGroupSeparator;

        string negativeSign = numberFormatInfo.NegativeSign;
 

        string keyInput = e.KeyChar.ToString();
 

        if (Char.IsDigit(e.KeyChar))

        {

            // Digits are OK

        }

        else if (keyInput.Equals(decimalSeparator) || keyInput.Equals(groupSeparator) ||

         keyInput.Equals(negativeSign))

        {

            // Decimal separator is OK

        }

        else if (e.KeyChar == '\b')

        {

            // Backspace key is OK

        }

        //    else if ((ModifierKeys & (Keys.Control | Keys.Alt)) != 0)

        //    {

        //     // Let the edit control handle control and alt key combinations

        //    }

        else if (this.allowSpace && e.KeyChar == ' ')

        {
 

        }

        else

        {

            // Consume this invalid key and beep

            e.Handled = true;

            //    MessageBeep();

        }

    }
 

    public int IntValue

    {

        get

        {

            return Int32.Parse(this.Text);

        }

    }
 

    public decimal DecimalValue

    {

        get

        {

            return Decimal.Parse(this.Text);

        }

    }
 

    public bool AllowSpace

    {

        set

        {

            this.allowSpace = value;

        }
 

        get

        {

            return this.allowSpace;

        }

    }

}

Open in new window

0
 
LVL 26

Expert Comment

by:Anurag Thakur
ID: 24396259
is it a web application or a windows application
0
 

Author Comment

by:mannevenu
ID: 24408938
Windows application
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.
A company’s greatest vulnerability is their email. CEO fraud, ransomware and spear phishing attacks are the no1 threat to a company’s security. Cybercrime is responsible for the largest loss of money to companies today with losses projected to r…

929 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now