• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 184
  • Last Modified:

How to validate TextBox inputs as they entered

Hi Experts,

How do I validate inputs to a TextBox and rejects unwanted inputs.  For example, I want the TextBox to only accepts numeric values only.
0
ambuli
Asked:
ambuli
3 Solutions
 
Jaime OlivaresSoftware ArchitectCommented:
Read this article about textbox validation:
http://www.codeproject.com/cs/miscctrl/validatedTextBox.asp
0
 
MikeMCSDCommented:
This works if you just want to check for Integers,
it won't work for numbers like 78,999.99 :

  public bool IsNumber(string sNumber)
    {
    bool Result = true;
    for (int i = 0; i < sNumber.Length; i++)
      {
      if (!Char.IsNumber(sNumber, i))
        {
        Result = false;
        return Result;
        }
      }
    return Result;
    }
0
 
Bob LearnedCommented:
I like when it is handled by the operating system:

using System;
using System.Diagnostics;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Windows.Forms;

public class NumericTextBox : TextBox
{

    public NumericTextBox()
    {

        InitializeComponent();

        this.SetNumericStyle();

    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            if (!((components == null)))
            {
                components.Dispose();
            }
        }
        base.Dispose(disposing);
    }
    private IContainer components;

    [DebuggerStepThrough()]
    private void InitializeComponent()
    {
        components = new Container();
    }

    [DllImport("user32", EntryPoint = "GetWindowLongA")]
    private static extern int GetWindowLong(IntPtr handle, int nIndex);

    [DllImport("user32", EntryPoint = "SetWindowLongA")]
    private static extern int SetWindowLong(IntPtr handle, int nIndex, int dwNewLong);
    private bool m_isNumericStyle = true;

    [DefaultValue(true)]
    public bool IsNumericStyle
    {
        get
        {
            return m_isNumericStyle;
        }
        set
        {
            m_isNumericStyle = value;
            this.SetNumericStyle();
        }
    }

    private void SetNumericStyle()
    {

        const int GWL_STYLE = (-16);
        const int ES_NUMBER = 0x2000;

        int styleCurrent = GetWindowLong(this.Handle, GWL_STYLE);
        int styleNew;

        if (this.IsNumericStyle)
            styleNew = styleCurrent | ES_NUMBER;
        else
            styleNew = styleCurrent | -ES_NUMBER;

        SetWindowLong(this.Handle, GWL_STYLE, styleNew);

    }

}

Bob
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now