Solved

C# Number Only Field with Backspace and Paste function

Posted on 2008-10-28
6
2,572 Views
Last Modified: 2012-05-05
Hello all,

I am working in C# 2008 Express and want to have my text field only accept numbers however still allow backspace and paste insertion.  I have pasted in what i have thus far which allows the just numbers and the backspace but I am failing to conquer the paste function.  Any help would be great thanks.

        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            //if (!Char.IsDigit(e.KeyChar)||!Char.IsControl(e.KeyChar))
            if ((!Char.IsDigit(e.KeyChar)) && (e.KeyChar != Convert.ToChar(Keys.Back)))
                e.Handled = true;
        }
0
Comment
Question by:Andrew Bass
  • 3
  • 2
6 Comments
 
LVL 1

Expert Comment

by:Nullable
ID: 22827748
Use this Code in the KeyDown Event



private void textBox1_KeyDown(object sender, KeyEventArgs e)

{

    // For Past Action

    if (e.Modifiers == Keys.Control && e.KeyCode == Keys.V)

        return;

    e.SuppressKeyPress = true;

}

Open in new window

0
 
LVL 26

Expert Comment

by:Anurag Thakur
ID: 22828366
void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.V && (e.Modifiers & Keys.Control) != Keys.None)
    {
        TextBox tb = sender as TextBox;
        string textToPaste =  Clipboard.GetText();
        tb.Paste();
        e.Handled = true;
        e.SuppressKeyPress = true;
        Console.WriteLine("Pasted: {0}", textToPaste);
    }
}

But that won't intercept the user clicking on Edit->Paste...

You can do that by inherting new control from the text box control and overriding WndProc in order to detect WM_PASTE message. Here is an example for an overriden WndProc

private const int WM_PASTE = 0x0302;
  protected override void WndProc(ref Message m)
  {
   if (m.Msg == WM_PASTE)
   {
    MessageBox.Show("Paste");
   }
   base.WndProc(ref m);
  }
0
 
LVL 1

Expert Comment

by:Nullable
ID: 22828389
in this code  :
void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.V && (e.Modifiers & Keys.Control) != Keys.None)
    {
        TextBox tb = sender as TextBox;
        string textToPaste =  Clipboard.GetText();
        tb.Paste();
        e.Handled = true;
        e.SuppressKeyPress = true;
        Console.WriteLine("Pasted: {0}", textToPaste);
    }
}

Shift + V is not work
0
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.

 
LVL 1

Author Comment

by:Andrew Bass
ID: 22832003
When I use your code i continue to get expected errors.
To clarify I DO WANT end users to be able to paste numbers into the text box field.  I have attached the coding in a txt doc if there are any ideas how to fix this up it would be appreciated.  Thanks
        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)

        {

            //if (!Char.IsDigit(e.KeyChar)||!Char.IsControl(e.KeyChar))

            if ((!Char.IsDigit(e.KeyChar)) && (e.KeyChar != Convert.ToChar(Keys.Back)))

                e.Handled = true;

        }
 

        private void textBox1_KeyDown(object sender, KeyEventArgs e)

        {

            if (e.KeyCode == Keys.V && (e.Modifiers & Keys.Control) != Keys.None)

                {

                TextBox tb = sender as TextBox;

                string textToPaste = Clipboard.GetText();

                tb.Paste();

                e.Handled = true;

                e.SuppressKeyPress = true;

                Console.WriteLine("Pasted: {0}", textToPaste);

                }

        }

Open in new window

0
 
LVL 1

Accepted Solution

by:
Nullable earned 500 total points
ID: 22870274
i have writen a Control
it is a FilteredTextbox
i Place my code for u with a sample

it have this featurse :
numeric filterDecimal filter ( numeric + float point (.))Email filter Custom Filter ( set a char set for desire)

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Drawing;

using System.Data;

using System.Linq;

using System.Text;

using System.Windows.Forms;

using System.Text.RegularExpressions;
 

namespace BM

{

    /// <summary>

    /// writed by Behrooz Mohammadi ( Nullabel )

    /// behrooz_pro@yahoo.com

    /// </summary>

    [DefaultBindingProperty("IntValue")]

    public partial class FilteredTextBox : TextBox

    {

        public FilteredTextBox()

        {

            InitializeComponent();

        }
 

        protected override void OnKeyPress(KeyPressEventArgs e)

        {

            base.OnKeyPress(e);

                                                                       

            if (!Active || e.KeyChar == '\b')

                return;
 

            if (Email)

            {

                return;

            }

            else

            {

                if (CustomFilter != "")

                {

                    if (CustomFilter.Contains(e.KeyChar))

                        return;

                }
 

                if (Numeric)

                {

                    if (char.IsNumber(e.KeyChar))

                        return;

                }
 

                if (AllowDecimals && !Text.Contains("."))

                    if (e.KeyChar == '.')

                        return;

            }
 

            e.Handled = true;

        }
 

        [Category("Setting")]

        public bool Active { get; set; }
 

        [Category("Setting")]

        public bool Numeric { get; set; }
 

        [Category("Setting")]

        public bool Email { get; set; }
 

        string _CustomFilter = "";

        private bool _allowDecimals = false;

        private string LastStr = "";
 

        [Category("Setting")]

        public string CustomFilter

        {

            get { return _CustomFilter; }

            set

            {

                _CustomFilter = value;

            }

        }
 

        [Category("Setting")]

        public bool AllowDecimals

        {

            get { return _allowDecimals; }

            set { _allowDecimals = value; }

        }
 

        [Bindable(true)]

        [Category("Setting")]

        public int? IntValue

        {

            get

            {

                if (string.IsNullOrEmpty(Text))

                    return null;
 

                int A;

                if (int.TryParse(Text, out A))

                    return A;

                else

                    return null;

            }

            set

            {

                if (value.HasValue)

                    this.Text = value.Value.ToString();

                else

                    Text = "";

            }

        }
 

        [Bindable(true)]

        [Category("Setting")]

        public decimal? DecimalValue

        {

            get

            {

                if (string.IsNullOrEmpty(Text))

                    return null;
 

                decimal A;

                if (decimal.TryParse(Text, out A))

                    return A;

                else

                    return null;

            }

            set

            {

                if (value.HasValue)

                    this.Text = value.Value.ToString();

                else

                    Text = "";

            }

        }
 

        protected override void OnTextChanged(EventArgs e)

        {

            if (!Active || string.IsNullOrEmpty(Text))

                return;
 

            if (Numeric)

                if (_allowDecimals)

                {

                    decimal k;

                    if (!decimal.TryParse(Text, out k))

                    {

                        int x = SelectionStart, l = SelectionLength;

                        this.Text = LastStr;

                        SelectionStart = x;

                        SelectionLength = l;

                        return;

                    }

                }

                else

                {

                    int k;

                    if (!int.TryParse(Text, out k))

                    {

                        int x = SelectionStart, l = SelectionLength;

                        this.Text = LastStr;

                        SelectionStart = x;

                        SelectionLength = l;

                        return;

                    }

                }

            LastStr = Text;

            base.OnTextChanged(e);

        }
 

        private void FilteredTextBox_Validating(object sender, CancelEventArgs e)

        {

            if (Email)

            {

                if (string.IsNullOrEmpty(Text))

                    return;
 

                string strRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +

                          @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +

                          @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";

                Regex re = new Regex(strRegex);

                if (re.IsMatch(Text))

                    return;

                else

                {

                    e.Cancel = true;

                    MessageBox.Show("Enter Valid Email.");

                }

            }

        }

    }

}
 

// Designer.cs file :
 

namespace BM

{

    partial class FilteredTextBox

    {

        /// <summary> 

        /// Required designer variable.

        /// </summary>

        private System.ComponentModel.IContainer components = null;
 

        /// <summary> 

        /// Clean up any resources being used.

        /// </summary>        

        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>

        protected override void Dispose(bool disposing)

        {

            if (disposing && (components != null))

            {

                components.Dispose();

            }

            base.Dispose(disposing);

        }
 

        #region Component Designer generated code
 

        /// <summary> 

        /// Required method for Designer support - do not modify 

        /// the contents of this method with the code editor.

        /// </summary>

        private void InitializeComponent()

        {

            this.SuspendLayout();

            // 

            // FilteredTextBox

            // 

            this.Validating += new System.ComponentModel.CancelEventHandler(this.FilteredTextBox_Validating);

            this.ResumeLayout(false);
 

        }
 

        #endregion

    }

}

Open in new window

FilterTextbox.zip
0
 
LVL 1

Author Closing Comment

by:Andrew Bass
ID: 31511010
Thanks for your help Nullable and the thoroughness!
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

Suggested Solutions

Title # Comments Views Activity
C# TextBox 11 30
Error when loading the database 16 56
C# Json POSt to Rest API 4 36
Wav problem 4 13
I was working on a PowerPoint add-in the other day and a client asked me "can you implement a feature which processes a chart when it's pasted into a slide from another deck?". It got me wondering how to hook into built-in ribbon events in Office.
You can of course define an array to hold data that is of a particular type like an array of Strings to hold customer names or an array of Doubles to hold customer sales, but what do you do if you want to coordinate that data? This article describes…
Get people started with the utilization of class modules. Class modules can be a powerful tool in Microsoft Access. They allow you to create self-contained objects that encapsulate functionality. They can easily hide the complexity of a process from…
This lesson covers basic error handling code in Microsoft Excel using VBA. This is the first lesson in a 3-part series that uses code to loop through an Excel spreadsheet in VBA and then fix errors, taking advantage of error handling code. This l…

912 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

20 Experts available now in Live!

Get 1:1 Help Now