Numeric TextBox

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Dmitry Karneyev

    #1

    Numeric TextBox

    How to make TextBox control that allows to input only numerics, currency etc
    ?
    Or can I download such stuff ?


  • Justin Weinberg

    #2
    Re: Numeric TextBox

    If you're not set on the textbox, check out the numericupdown.

    If you are set on the textbox, handle the Validating event, set up a try
    block and call Decimal.Parse (or whatever type is appropraite to your
    scenario). On the exception, cancel the validation.

    --

    Justin Weinberg
    Designing a PrintDocument? Drawing to forms?
    Check out GDI+ Architect at www.mrgsoft.com


    "Dmitry Karneyev" <karneyev@msn.c om> wrote in message
    news:utz5TX7lDH A.2444@TK2MSFTN GP09.phx.gbl...[color=blue]
    > How to make TextBox control that allows to input only numerics, currency[/color]
    etc[color=blue]
    > ?
    > Or can I download such stuff ?
    >
    >[/color]


    Comment

    • Aymeric GAURAT APELLI

      #3
      Re: Numeric TextBox

      Here is what you need (I hope):

      ------------------------- CurrencyTextBox Validator.cs
      using System;
      using System.Componen tModel;
      using System.Collecti ons;
      using System.Diagnost ics;
      using System.Windows. Forms;


      namespace YourApp
      {
      /// <summary>
      /// Summary description for CurrencyTextBox Validator.
      /// </summary>
      public class CurrencyTextBox Validator : System.Windows. Forms.TextBox
      {
      char keyCharValue;

      public CurrencyTextBox Validator()
      {
      InitializeCompo nent();
      }

      #region Initialize
      private void InitializeCompo nent()
      {
      this.KeyPress += new
      System.Windows. Forms.KeyPressE ventHandler(thi s.CurrencyTextB ox_KeyPress);
      this.BorderStyl e = System.Windows. Forms.BorderSty le.FixedSingle;
      this.TextChange d += new EventHandler(th is.CurrencyText Box_TextChanged );
      }
      #endregion

      #region public methods

      /// <summary>
      /// Get the Currency Value (without space) of the TextBox
      /// </summary>
      /// <returns> -1 when an error occurs</returns>
      public int GetValueOfCurre ncy()
      {
      try
      {
      if (this.Text != "")
      return (Convert.ToInt3 2(this.Text.Rep lace(" ", "")));
      else
      return -1;
      }
      catch(Exception )
      {
      return -1;
      }
      }

      /// <summary>
      /// Take the Currency Value (without space) and put it in the TextBox
      /// </summary>
      public void PutCurrencyIn(s tring currencyValue)
      {
      this.Text = currencyValue;
      AddSpaceInNumbe r();
      }

      #endregion

      #region private methods
      private void AddSpaceInNumbe r()
      {
      for (int posOfSpaceInTex t = this.Text.Lengt h; posOfSpaceInTex t > 3;
      posOfSpaceInTex t -= 3)
      this.Text = this.Text.Inser t(posOfSpaceInT ext - 3, " ");
      }
      #endregion

      #region mask handlers
      private void CurrencyTextBox _KeyPress(objec t sender,
      System.Windows. Forms.KeyPressE ventArgs e)
      {
      keyCharValue = e.KeyChar;
      }

      private void CurrencyTextBox _TextChanged(ob ject sender, System.EventArg s
      e)
      {
      this.TextChange d -= new EventHandler(th is.CurrencyText Box_TextChanged );
      if (!Char.IsDigit( keyCharValue) && keyCharValue != ' ' &&
      Convert.ToInt32 (keyCharValue) != 8)
      {
      this.Text = this.Text.Repla ce(keyCharValue .ToString(), "");
      this.Select(thi s.Text.Length, 0);
      }
      else
      {
      this.SuspendLay out();
      this.Text = this.Text.Repla ce(" ", "");
      AddSpaceInNumbe r();
      this.Select(thi s.Text.Length, 0);
      this.ResumeLayo ut();
      }
      this.TextChange d += new EventHandler(th is.CurrencyText Box_TextChanged );
      }
      #endregion

      }
      }

      ------------------------
      Best regards.

      --
      Aymeric GAURAT APELLI
      Consultant 3IE (http://www.3ie.org)

      "Dmitry Karneyev" <karneyev@msn.c om> wrote in message
      news:utz5TX7lDH A.2444@TK2MSFTN GP09.phx.gbl...[color=blue]
      > How to make TextBox control that allows to input only numerics, currency[/color]
      etc[color=blue]
      > ?
      > Or can I download such stuff ?
      >
      >[/color]


      Comment

      • Dmitry Karneyev

        #4
        Re: Numeric TextBox

        Great stuff!
        There is one another little thing.
        This control doesn't allow to inut values with dot, I mean "123.456"
        It would be cool to implement such functionality.

        But anyway, thanks!

        "Aymeric GAURAT APELLI" <gaurat_a@3ie.o rg> ÓÏÏÂÝÉÌ/ÓÏÏÂÝÉÌÁ × ÎÏ×ÏÓÔÑÈ
        ÓÌÅÄÕÀÝÅÅ: news:ORHlde7lDH A.1284@TK2MSFTN GP09.phx.gbl...[color=blue]
        > Here is what you need (I hope):
        >
        > ------------------------- CurrencyTextBox Validator.cs
        > using System;
        > using System.Componen tModel;
        > using System.Collecti ons;
        > using System.Diagnost ics;
        > using System.Windows. Forms;
        >
        >
        > namespace YourApp
        > {
        > /// <summary>
        > /// Summary description for CurrencyTextBox Validator.
        > /// </summary>
        > public class CurrencyTextBox Validator : System.Windows. Forms.TextBox
        > {
        > char keyCharValue;
        >
        > public CurrencyTextBox Validator()
        > {
        > InitializeCompo nent();
        > }
        >
        > #region Initialize
        > private void InitializeCompo nent()
        > {
        > this.KeyPress += new
        > System.Windows. Forms.KeyPressE ventHandler(thi s.CurrencyTextB ox_KeyPress);
        > this.BorderStyl e = System.Windows. Forms.BorderSty le.FixedSingle;
        > this.TextChange d += new EventHandler(th is.CurrencyText Box_TextChanged );
        > }
        > #endregion
        >
        > #region public methods
        >
        > /// <summary>
        > /// Get the Currency Value (without space) of the TextBox
        > /// </summary>
        > /// <returns> -1 when an error occurs</returns>
        > public int GetValueOfCurre ncy()
        > {
        > try
        > {
        > if (this.Text != "")
        > return (Convert.ToInt3 2(this.Text.Rep lace(" ", "")));
        > else
        > return -1;
        > }
        > catch(Exception )
        > {
        > return -1;
        > }
        > }
        >
        > /// <summary>
        > /// Take the Currency Value (without space) and put it in the TextBox
        > /// </summary>
        > public void PutCurrencyIn(s tring currencyValue)
        > {
        > this.Text = currencyValue;
        > AddSpaceInNumbe r();
        > }
        >
        > #endregion
        >
        > #region private methods
        > private void AddSpaceInNumbe r()
        > {
        > for (int posOfSpaceInTex t = this.Text.Lengt h; posOfSpaceInTex t > 3;
        > posOfSpaceInTex t -= 3)
        > this.Text = this.Text.Inser t(posOfSpaceInT ext - 3, " ");
        > }
        > #endregion
        >
        > #region mask handlers
        > private void CurrencyTextBox _KeyPress(objec t sender,
        > System.Windows. Forms.KeyPressE ventArgs e)
        > {
        > keyCharValue = e.KeyChar;
        > }
        >
        > private void CurrencyTextBox _TextChanged(ob ject sender, System.EventArg s
        > e)
        > {
        > this.TextChange d -= new EventHandler(th is.CurrencyText Box_TextChanged );
        > if (!Char.IsDigit( keyCharValue) && keyCharValue != ' ' &&
        > Convert.ToInt32 (keyCharValue) != 8)
        > {
        > this.Text = this.Text.Repla ce(keyCharValue .ToString(), "");
        > this.Select(thi s.Text.Length, 0);
        > }
        > else
        > {
        > this.SuspendLay out();
        > this.Text = this.Text.Repla ce(" ", "");
        > AddSpaceInNumbe r();
        > this.Select(thi s.Text.Length, 0);
        > this.ResumeLayo ut();
        > }
        > this.TextChange d += new EventHandler(th is.CurrencyText Box_TextChanged );
        > }
        > #endregion
        >
        > }
        > }
        >
        > ------------------------
        > Best regards.
        >
        > --
        > Aymeric GAURAT APELLI
        > Consultant 3IE (http://www.3ie.org)
        >
        > "Dmitry Karneyev" <karneyev@msn.c om> wrote in message
        > news:utz5TX7lDH A.2444@TK2MSFTN GP09.phx.gbl...[color=green]
        > > How to make TextBox control that allows to input only numerics, currency[/color]
        > etc[color=green]
        > > ?
        > > Or can I download such stuff ?
        > >
        > >[/color]
        >
        >[/color]


        Comment

        • Dmitry Karneyev

          #5
          Re: Numeric TextBox

          I need such control to bind numeric data from database withWindows Form.
          Just for intersest: here is modified version of this control with "123,456"
          functionality.

          using System;

          using System.Componen tModel;

          using System.Collecti ons;

          using System.Diagnost ics;

          using System.Windows. Forms;

          namespace YourApp

          {

          /// <summary>

          /// Summary description for NumericTextBox.

          /// </summary>

          public class NumericTextBox : System.Windows. Forms.TextBox

          {

          /// <summary>

          /// Required designer variable.

          /// </summary>

          private System.Componen tModel.Containe r components = null;

          public NumericTextBox( )

          {

          // This call is required by the Windows.Forms Form Designer.

          InitializeCompo nent();

          // TODO: Add any initialization after the InitializeCompo nent call

          }

          /// <summary>

          /// Clean up any resources being used.

          /// </summary>

          protected override void Dispose( bool disposing )

          {

          if( disposing )

          {

          if(components != null)

          {

          components.Disp ose();

          }

          }

          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 InitializeCompo nent()

          {

          components = new System.Componen tModel.Containe r();

          this.KeyPress += new
          System.Windows. Forms.KeyPressE ventHandler(thi s.NumericTextBo x_KeyPress);

          //this.BorderStyl e = System.Windows. Forms.BorderSty le.FixedSingle;

          this.TextChange d += new EventHandler(th is.NumericTextB ox_TextChanged) ;

          }

          #endregion


          char keyCharValue;


          protected void NumericTextBox_ KeyPress(object sender,
          System.Windows. Forms.KeyPressE ventArgs e)

          {

          keyCharValue = e.KeyChar;

          // we are not going to continue hadling ','

          if(e.KeyChar == ',')

          {

          e.Handled = true;

          }

          }

          /// <summary>

          /// Inserting ',' into Text property instead of '.'

          /// </summary>

          protected void DoDotStuff()

          {

          int dotPosition = this.Text.LastI ndexOf(".");

          int sepPosition = this.Text.Index Of(",");

          // ÅÓÌÉ ÔÏÞËÕ ××ÅÌÉ ÎÅ × ÎÁÞÁÌÅ ÓÔÒÏËÉ É ÄÏ ÜÔÏÇÏ ÔÏÖÅ ÎÅ ÂÙÌÏ ××ÅÄÅÎÏ ÔÏÞÅË

          if((dotPosition > 0) && (sepPosition < 0))

          {

          this.Text = this.Text.Repla ce(keyCharValue .ToString(), ",");

          this.Select(thi s.Text.Length, 0);

          }

          // ÕÄÁÌÑÅÍ ÔÏ, ÞÔÏ ××ÅÌÉ

          else

          {

          if((sepPosition > 0) && (dotPosition > 0))

          {

          this.Text = this.Text.Remov e(sepPosition, 1);

          this.Text = this.Text.Repla ce(keyCharValue .ToString(), ",");

          this.Select(dot Position, 0);

          }

          else

          {

          this.Text = this.Text.Remov e(dotPosition, 1);

          this.Select(sep Position, 0);

          }

          }

          }

          // private void DoSepStuff()

          // {

          // int anotherSepPosit ion = this.Text.LastI ndexOf(",");

          // int sepPosition = this.Text.Index Of(",");

          // // ÅÓÌÉ ÐÏ×ÔÏÒÎÙÊ ××ÏÄ ÚÁÐÑÔÏÊ ÉÌÉ ÏÎÁ ÐÅÒ×ÁÑ × ÓÔÒÏËÅ

          // if((anotherSepP osition != sepPosition) || (sepPosition == 0))

          // {

          // this.Text = this.Text.Remov e(sepPosition, 1);

          // this.Select(ano therSepPosition , 0);

          // }

          // }

          protected void NumericTextBox_ TextChanged(obj ect sender, System.EventArg s e)

          {

          this.TextChange d -= new EventHandler(th is.NumericTextB ox_TextChanged) ;

          this.SuspendLay out();

          if (!Char.IsDigit( keyCharValue))

          {

          switch (keyCharValue)

          {

          case '.':

          DoDotStuff();

          break;

          default:

          // removing that which was inserted

          int badCharacterPos ition = this.Text.Index Of(keyCharValue .ToString());

          this.Text = this.Text.Repla ce(keyCharValue .ToString(), "");

          this.Select(bad CharacterPositi on, 0);

          break;

          }

          }

          else

          {

          this.Text = this.Text.Repla ce(" ", "");

          this.Select(thi s.Text.Length, 0);

          }

          this.ResumeLayo ut();

          this.TextChange d += new EventHandler(th is.NumericTextB ox_TextChanged) ;

          }

          /// <summary>

          /// Get the Currency Value (without space) of the TextBox

          /// </summary>

          /// <returns> -1 when an error occurs</returns>

          public decimal GetValueOfCurre ncy()

          {

          try

          {

          if (this.Text != "")

          return (Convert.ToDeci mal(this.Text.R eplace(" ", "")));

          else

          return -1;

          }

          catch(Exception )

          {

          return -1;

          }

          }

          /// <summary>

          /// Take the Currency Value (without space) and put it in the TextBox

          /// </summary>

          public void PutDecimalIn(de cimal decimalValue)

          {

          try

          {

          this.Text = decimalValue.To String();

          }

          catch(Exception )

          {

          this.Text = "";

          }

          }

          }

          }


          Comment

          • Ignacio Machin \( .NET/ C#  MVP \)

            #6
            Re: Numeric TextBox

            Helo,

            All you have to do is override CreateParams property , below you will find
            the code for this class, it's derived from TextBox and only redefine that
            property.
            Note, this do not check the value you create the control with, only the
            input from the user.


            public class NumericTextBox : TextBox

            {

            protected override CreateParams CreateParams

            {

            get

            {

            CreateParams cp = base.CreatePara ms;

            cp.Style |= 0x2000; // ES_NUMBER ( defined in WinUser.h )

            return cp;

            }

            }

            }

            Hope this help,

            --
            Ignacio Machin,
            ignacio.machin AT dot.state.fl.us
            Florida Department Of Transportation

            "Dmitry Karneyev" <karneyev@msn.c om> wrote in message
            news:utz5TX7lDH A.2444@TK2MSFTN GP09.phx.gbl...[color=blue]
            > How to make TextBox control that allows to input only numerics, currency[/color]
            etc[color=blue]
            > ?
            > Or can I download such stuff ?
            >
            >[/color]


            Comment

            Working...