Text Box Numeric Entry

Jack0987 1 Reputation point
2022-11-20T18:41:09.557+00:00

I would like to enter numeric only input to more than one textBox. Instead of repeating the same code (as I have done in my sample attached code) for each Box, could I have one method for all?

using System;  
using System.Collections.Generic;  
using System.ComponentModel;  
using System.Data;  
using System.Drawing;  
using System.Linq;  
using System.Text;  
using System.Windows.Forms;  
  
namespace TestingNumericInput  
{  
    public partial class Form1 : Form  
    {  
        public Form1()  
        {  
            InitializeComponent();  
        }  
  
        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)  
        {  
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) &&  
                (e.KeyChar != '.'))  
            {  
                e.Handled = true;  
            }  
  
            // only allow one decimal point  
            if ((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.') > -1))  
            {  
                e.Handled = true;  
            }  
        }  
  
        private void textBox1_TextChanged(object sender, EventArgs e)  
        {  
            if (textBox1.Text.FirstOrDefault() == '.')  
            {  
                textBox1.Text = "0" + textBox1.Text;  
                textBox1.Select(textBox1.Text.Length, 0);  
            }  
        }  
  
        private void textBox2_KeyPress(object sender, KeyPressEventArgs e)  
        {  
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) &&  
                (e.KeyChar != '.'))  
            {  
                e.Handled = true;  
            }  
  
            // only allow one decimal point  
            if ((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.') > -1))  
            {  
                e.Handled = true;  
            }  
        }  
  
        private void textBox2_TextChanged(object sender, EventArgs e)  
        {  
            if (textBox2.Text.FirstOrDefault() == '.')  
            {  
                textBox2.Text = "0" + textBox2.Text;  
                textBox2.Select(textBox2.Text.Length, 0);  
            }  
        }  
  
          
    }  
}  
  
Developer technologies Windows Forms
Developer technologies C#
{count} votes

2 answers

Sort by: Most helpful
  1. Castorix31 90,521 Reputation points
    2022-11-20T20:41:07.637+00:00

    (the windows-app-sdk-text-rendering tag is wrong, it should be dotnet-csharp or winforms...)

    Derive a Class , like :

    public class MyTextBox : System.Windows.Forms.TextBox  
    {  
        // code...  
    }  
    

  2. Karen Payne MVP 35,586 Reputation points Volunteer Moderator
    2022-11-20T22:09:59.767+00:00

    Use a dedicated number TextBox as shown below.

    public class NumericTextBox : TextBox  
    {  
        private readonly char _decimalSeparator =  
            CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator[0];  
      
        public NumericTextBox()  
        {  
            TextAlign = HorizontalAlignment.Right;  
        }  
      
        protected override void OnKeyPress(KeyPressEventArgs e)  
        {  
      
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != _decimalSeparator)  
            {  
                e.Handled = true;  
            }  
      
            if (e.KeyChar == _decimalSeparator && Text.IndexOf(_decimalSeparator) > -1)  
            {  
                e.Handled = true;  
            }  
      
            base.OnKeyPress(e);  
      
        }  
      
        [Browsable(false)]  
        public int Integer => int.TryParse(Text, out var value) ? value : 0;  
        [Browsable(false)]  
        public decimal Decimal => decimal.TryParse(Text, out var value) ? value : 0;  
        [Browsable(false)]  
        public double Double => double.TryParse(Text, out var value) ? value : 0;  
      
        public bool HasValue() => !string.IsNullOrWhiteSpace(Text);  
      
        int WM_PASTE = 0x0302;  
        protected override void WndProc(ref Message message)  
        {  
            if (message.Msg == WM_PASTE)  
            {  
                var clipboardData = Clipboard.GetDataObject();  
                var input = (string)clipboardData?.GetData(typeof(string))!;  
                int count = 0;  
      
                foreach (var c in input)  
                {  
                    if (c == _decimalSeparator)  
                    {  
                        count++;  
                        if (count > 1)  
                        {  
                            return;  
                        }  
                    }  
                }  
      
                foreach (var character in input)  
                {  
      
                    if (!char.IsControl(character) && !char.IsDigit(character) && character != _decimalSeparator)  
                    {  
                        message.Result = (IntPtr)0;  
                        return;  
                    }  
      
                }  
            }  
      
            base.WndProc(ref message);  
      
        }  
    }  
    

    To get numbers from the above use the properties Integer Decimal or Double and to determine if the value is 0 use HasValue

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.