Confessions of a .NET Developer!

Allow numbers or letters and disable right-click in textbox

I have seen a number of people asking how to allow only numbers to be added in to a textbox, sometimes only letters etc. Also to disable right-click to disable pasting. One such question can be found here: http://www.codeproject.com/Answers/208641/Wish-to-use-text-box-to-only-allow-numeric-Data-en/?cmt=114369#answer4 to which my friend Chanakya(a pro-photographer with excellent technical skills) gave an excellent, sweet and simple answer, also do read the comments. I got inspiration from him to write this post.
So I will create a new TextBox which will handle all the above things. Its a “derived” control where I create a class which derives from TextBox class.

Here is the class:

    class NewTextBox : System.Windows.Forms.TextBox
    {
        private ContextMenu OrgContextMenu;
        private RestrictType _restrictOptions = RestrictType.None;
        public RestrictType RestrictOptions
        {
            get { return _restrictOptions; }
            set { _restrictOptions = value; }
        }

        private bool _allowPaste = true;
        private ContextMenu PrevContextMenu { get; set; }
        private bool _setOnceFlag = false;

        public bool AllowPaste
        {
            get { return _allowPaste; }
            set
            {
                _allowPaste = value;
                DisableRightClick(value);
            }
        }

        protected override void OnKeyDown(KeyEventArgs e)
        {
            //To only allow numbers 
            if (RestrictOptions == RestrictType.OnlyNumbers)
            {
                if (char.IsNumber((char)e.KeyValue) || (((char)e.KeyData) == '\b'))
                {
                    e.SuppressKeyPress = false;
                }
                else { e.SuppressKeyPress = true; }
            }

            // To only allow letters
            else if (RestrictOptions == RestrictType.OnlyLetters)
            {
                if (char.IsLetter((char)e.KeyValue) || (((char)e.KeyData) == '\b'))
                {
                    e.SuppressKeyPress = false;
                }
                else { e.SuppressKeyPress = true; }
            }

            //To only allow 0's and 1's
            else if (RestrictOptions == RestrictType.OnlyBinary)
            {
                if (((char)e.KeyValue).Equals('1') || ((char)e.KeyValue).Equals('0')
                    || (((char)e.KeyData) == '\b'))
                {
                    e.SuppressKeyPress = false;
                }
                else { e.SuppressKeyPress = true; }
            }
        }

        //To disable Cntl + V for pasting
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (AllowPaste.Equals(false))
            {
                if (keyData == (Keys.Control | Keys.V))
                {
                    return true;
                }
                else { return false; }
            }
            else { return false; }
        }

        // Disable Right-click for pasting
        private void DisableRightClick(bool enable)
        {
            if (_setOnceFlag == false)
            {
                OrgContextMenu = this.ContextMenu;
                _setOnceFlag = true;
            }
            if (enable.Equals(false))
            {
                // This will create a new ContextMenu with no options, hence no dropdown will be visible.
                this.ContextMenu = new ContextMenu();
            }
            // Set the original context menu.
            else
            { this.ContextMenu = OrgContextMenu; }
        }
    }

And an enum called RestrictType:

    public enum RestrictType
    {
        OnlyNumbers,
        OnlyLetters,
        OnlyBinary,
        None
    }

The code is self-explanatory. To briefly explain, I have created three properties, one is RestrictOptions which is of type RestrictType to let the user choose he/she wants allow numbers or letters or binary. Then the second property is to whether to disable pasting or not. The ProcessCmdKey function will take care of Ctrl + V, disabling it whenever the combination is used, and then using DiableRightClick function to disable Right-click by showing an empty ContextMenu. These two will be set by the user and by default, AllowPaste is true and RestrictType is None. The other property which is private is OrgContextMenu which will store the initial and original ContextMenu of the Textbox which will be set only one time.

Time to use it:

        public Form1()
        {
            InitializeComponent();
            newTextBox1.RestrictOptions = RestrictType.OnlyNumbers;
            newTextBox1.AllowPaste = false;
        }

Please do give your comments and valuable suggestions for improvement. 🙂
Happy Coding!

Advertisements

June 26, 2011 - Posted by | C Sharp, Winforms

1 Comment »

  1. Hi,
    Thanks for the useful post. I would like to use this code but don’t know where I need to go to do this as I am new to worpress.com so can you please break it down into smaller steps ie dashboard – then where??? appearances, settings, tools etc and get back to me
    Many thanks
    Cheers Jo

    Comment by storyteller10 | July 29, 2011 | Reply


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: