Numbered TextBox

Assalamu Alaykum..

ntxtbox

This is a simple class in C# which validates a textbox to accept numbers Only..


    class NumberedTextBox
    {
        TextBox _txtBox = new TextBox();
        Label _ErrorProviderLabel = new Label();

        public NumberedTextBox(TextBox txtBox, Label ErrorProviderLabel)
        {
            txtBox.BackColor = Color.White;
            txtBox.ReadOnly = true;
            _txtBox = txtBox;
            _ErrorProviderLabel = ErrorProviderLabel;
            txtBox.KeyDown += new System.Windows.Forms.KeyEventHandler(txtBox_KeyDown);
            txtBox.KeyUp += new System.Windows.Forms.KeyEventHandler(txtBox_KeyUp);
        }

        private void txtBox_KeyUp(object sender, System.Windows.Forms.KeyEventArgs e)
        {
            _txtBox.ReadOnly = true;
        }

        private void txtBox_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Back)
            {
                _txtBox.ReadOnly = false;
                if (_ErrorProviderLabel != null)
                    _ErrorProviderLabel.Text = "";
                return;
            }
            else
            {
                for (int i = 0; i < 10; i++)
                {
                    if (e.KeyCode.ToString() == "D" + i.ToString())
                    {
                        _txtBox.ReadOnly = false;
                        if (_ErrorProviderLabel != null)
                            _ErrorProviderLabel.Text = "";
                        break;
                    }
                    if (_ErrorProviderLabel != null)
                        _ErrorProviderLabel.Text = "NumberedTextBox can accept numbers ONLY!";
                }
            }
        }
    }


Simply, the idea is to check the pressed key in KeyDown event if it's a number or not.. If it was number set ReadOnly to false, else set ReadOnly to true.


public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            new NumberedTextBox(txtBoxBalance, label2);
        }
    }

THAT'S ALL !!

Download Source Code

Advertisements

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: