Decimal TextBox Mk2

Decided my decimal textbox was a bit shit so had another quick go this afternoon, this time I did away with pasting altogether and disabled right click on the control by creating a blank contextmenu and assigning it to the textbox. Anyway here it is:


using System;
using System.Windows.Forms;

namespace DecimalTextBox
{
    public partial class DTB : TextBox
    {
        public int DecimalLength { get; set; }
        int[] numZeros;
        ContextMenu cmPaste = new ContextMenu();

        public DTB()
        {
            this.ContextMenu = cmPaste;  
        }

        protected override void OnKeyPress(KeyPressEventArgs e)
        {
            e.Handled = CheckDecimal(this, e, DecimalLength);
        }

        protected override void OnLeave(EventArgs e)
        {
            if (this.Text == "")
                this.Text += "0";
            if (this.Text.IndexOf(".") == -1)
                this.Text += ".";
                        
            numZeros = new int[this.Text.IndexOf(".") + DecimalLength - this.Text.Length + 1];

            if (this.Text.IndexOf(".") >= this.Text.Length - DecimalLength)
            {
                for (int i = 0; i < numZeros.Length; i++)
                {
                    numZeros[i] = 0;
                    this.Text += numZeros[i];
                }
            }
        }
        
        private static bool CheckDecimal(object sender, KeyPressEventArgs e, int numDecimals)
        {
            if (char.IsNumber(e.KeyChar) || e.KeyChar == '.')
            {
                TextBox tb = sender as TextBox;
                int cursorPosLeft = tb.SelectionStart;
                int cursorPosRight = tb.SelectionStart + tb.SelectionLength;
 
                string result = tb.Text.Substring(0, cursorPosLeft) + e.KeyChar + tb.Text.Substring(cursorPosRight);
                string[] parts = result.Split('.');
                
                if (parts.Length > 1)
                {
                    if (parts[1].Length > numDecimals || parts.Length > 2)
                    {
                        return true;
                    }
                }
                return false;
            }
            else return (e.KeyChar != (char)Keys.Back);
        }
    }
}
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