Click here to Skip to main content
15,893,368 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
using System;
using System.Windows;
namespace CommonControlLibrary
{
    public partial class NumericTextbox : System.Windows.Controls.TextBox
    {
       

        public NumericTextbox()
            : base()
        {
            this.AddHandler(System.Windows.DataObject.PastingEvent, new System.Windows.DataObjectPastingEventHandler(this.TextBoxPasting));
        }

        protected override void OnPreviewTextInput(System.Windows.Input.TextCompositionEventArgs e)
        {
            base.OnPreviewTextInput(e);
            e.Handled = !IsTextAllowed(e.Text);
        }

        private bool IsTextAllowed(string text)
        {
            System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex("[^0-9]+");
            return !regex.IsMatch(text);
        }

        private void TextBoxPasting(object sender, System.Windows.DataObjectPastingEventArgs e)
        {
            if (e.DataObject.GetDataPresent(typeof(System.String)))
            {
                System.String text = (System.String)e.DataObject.GetData(typeof(System.String));
                if (!IsTextAllowed(text))
                    e.CancelCommand();
            }

            else
                e.CancelCommand();

        }
    }
}
Posted
Updated 1-Nov-14 11:16am
v2

1 solution

Thoughts:

0) I recommend you make the regex a private static field rather than a local variable. Definitely don't keep instantiating it.

1) Similarly, I would make a private static field for typeof(System.String) .


Other than that, do you not know how to define a property?
 
Share this answer
 
Comments
Mahesh Alappuzha 3-Nov-14 1:21am    
how it possible? Can you Help

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900