Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Validating textboxes in C#

Validating textboxes in C#

Scheduled Pinned Locked Moved C#
csharpdatabasehelpquestion
13 Posts 8 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • X Offline
    X Offline
    Xonel
    wrote on last edited by
    #1

    Hi This code here below allows only numbers and one decimal point to be typed on a textbox. It does not prevent you from: 1. Saving nulls in the database 2. From pasting any other character(words, asterisks,numbers etc) to the textbox. What do i have to add to the code to prevent the two problems from occurring?? Here is my code:

        private void txtBalance\_TextChanged(object sender, EventArgs e)
        {
            txtBalance.KeyPress += new KeyPressEventHandler(numbercheck\_KeyPress);
        }
        private void numbercheck\_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;
            }
        }
    

    Please help me figure out Thanks

    N B B P D 5 Replies Last reply
    0
    • X Xonel

      Hi This code here below allows only numbers and one decimal point to be typed on a textbox. It does not prevent you from: 1. Saving nulls in the database 2. From pasting any other character(words, asterisks,numbers etc) to the textbox. What do i have to add to the code to prevent the two problems from occurring?? Here is my code:

          private void txtBalance\_TextChanged(object sender, EventArgs e)
          {
              txtBalance.KeyPress += new KeyPressEventHandler(numbercheck\_KeyPress);
          }
          private void numbercheck\_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;
              }
          }
      

      Please help me figure out Thanks

      N Offline
      N Offline
      Not Active
      wrote on last edited by
      #2

      First, you don't want to add the KeyPressEventHandler in the in the TextChanged event. Every time this event is fired it will add a new event handler, you only need it added once in your form load or in it method, or declaratively in the markup. Before saving to the database you should validate the input, KeyPressEventHandler has nothing to do with this.


      Failure is not an option; it's the default selection.

      X V 2 Replies Last reply
      0
      • N Not Active

        First, you don't want to add the KeyPressEventHandler in the in the TextChanged event. Every time this event is fired it will add a new event handler, you only need it added once in your form load or in it method, or declaratively in the markup. Before saving to the database you should validate the input, KeyPressEventHandler has nothing to do with this.


        Failure is not an option; it's the default selection.

        X Offline
        X Offline
        Xonel
        wrote on last edited by
        #3

        A simple example please?? :)

        N T 2 Replies Last reply
        0
        • X Xonel

          Hi This code here below allows only numbers and one decimal point to be typed on a textbox. It does not prevent you from: 1. Saving nulls in the database 2. From pasting any other character(words, asterisks,numbers etc) to the textbox. What do i have to add to the code to prevent the two problems from occurring?? Here is my code:

              private void txtBalance\_TextChanged(object sender, EventArgs e)
              {
                  txtBalance.KeyPress += new KeyPressEventHandler(numbercheck\_KeyPress);
              }
              private void numbercheck\_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;
                  }
              }
          

          Please help me figure out Thanks

          B Offline
          B Offline
          Bernhard Hiller
          wrote on last edited by
          #4

          Rather than trying to prevent "wrong" input, you should check the data when the user has finished input. Even when you prevent copy/paste of invalid data, some other technology might be used to get a "wrong" input into the box, e.g. a WM_SETTEXT message (think of assistive technologies). The "Validate" event of the textbox is a good place to do so.

          1 Reply Last reply
          0
          • X Xonel

            A simple example please?? :)

            N Offline
            N Offline
            Not Active
            wrote on last edited by
            #5

            You need an example of string.IsNullOrEmpty? Or how to validate a string :confused: if so then you need more help than can be given here.


            Failure is not an option; it's the default selection.

            1 Reply Last reply
            0
            • X Xonel

              A simple example please?? :)

              T Offline
              T Offline
              taha bahraminezhad Jooneghani
              wrote on last edited by
              #6

              if(string.IsNullOrEmpty(TextBox1.Text)){}

              V 1 Reply Last reply
              0
              • T taha bahraminezhad Jooneghani

                if(string.IsNullOrEmpty(TextBox1.Text)){}

                V Offline
                V Offline
                Vipin_Arora
                wrote on last edited by
                #7

                If u only want to validate decimal, then you can try following code at textbox change event:

                    private void textBox1\_TextChanged(object sender, EventArgs e)
                    {
                        if (textBox1.Text.Trim() != "")
                        {
                            decimal j;
                            if (!decimal.TryParse(textBox1.Text, out j))
                            {
                                MessageBox.Show("Not allowed!!!");
                                textBox1.Text = "";
                            }
                        }
                    }
                

                Here, replace "textBox1" with your textbox ID.

                1 Reply Last reply
                0
                • N Not Active

                  First, you don't want to add the KeyPressEventHandler in the in the TextChanged event. Every time this event is fired it will add a new event handler, you only need it added once in your form load or in it method, or declaratively in the markup. Before saving to the database you should validate the input, KeyPressEventHandler has nothing to do with this.


                  Failure is not an option; it's the default selection.

                  V Offline
                  V Offline
                  Vipin_Arora
                  wrote on last edited by
                  #8

                  If u only want to validate decimal, then you can try following code at textbox change event:

                  void textBox1_TextChanged(object sender, EventArgs e)
                  {
                  if (textBox1.Text.Trim() != "")
                  {
                  decimal j;
                  if (!decimal.TryParse(textBox1.Text, out j))
                  {
                  MessageBox.Show("Not allowed!!!");
                  textBox1.Text = "";
                  }
                  }
                  }

                  private Here, replace "textBox1" with your textbox ID.

                  1 Reply Last reply
                  0
                  • X Xonel

                    Hi This code here below allows only numbers and one decimal point to be typed on a textbox. It does not prevent you from: 1. Saving nulls in the database 2. From pasting any other character(words, asterisks,numbers etc) to the textbox. What do i have to add to the code to prevent the two problems from occurring?? Here is my code:

                        private void txtBalance\_TextChanged(object sender, EventArgs e)
                        {
                            txtBalance.KeyPress += new KeyPressEventHandler(numbercheck\_KeyPress);
                        }
                        private void numbercheck\_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;
                            }
                        }
                    

                    Please help me figure out Thanks

                    B Offline
                    B Offline
                    BobJanova
                    wrote on last edited by
                    #9

                    The database is irrelevant to this question. Your database schema should prevent nulls, and you want a control that gives you a double. A good numeric text box should:

                    • Hook TextChanged to make sure that the value can never be invalid, e.g. if you try to paste into it, set the text programatically (e.g. through data binding) or any other way of putting text in there. Note that 'valid content' isn't necessarily a valid number, because you need to allow intermediate input that someone will type while entering a number. For example '', '-', '3.', '6E' (if supporting exponential notation) and the like should be allowed. You can find or write a regex for this part.
                    • Hook the keyboard input events (KeyPress should be enough) to reject any characters that can never be allowed, e.g. anything but numbers, or a minus sign in an empty field, or a dot. This prevents the TextChanged handler from firing, wiping the invalid character but resetting the caret.
                    • Have a numeric Value property that you can read and write in code.
                    1 Reply Last reply
                    0
                    • X Xonel

                      Hi This code here below allows only numbers and one decimal point to be typed on a textbox. It does not prevent you from: 1. Saving nulls in the database 2. From pasting any other character(words, asterisks,numbers etc) to the textbox. What do i have to add to the code to prevent the two problems from occurring?? Here is my code:

                          private void txtBalance\_TextChanged(object sender, EventArgs e)
                          {
                              txtBalance.KeyPress += new KeyPressEventHandler(numbercheck\_KeyPress);
                          }
                          private void numbercheck\_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;
                              }
                          }
                      

                      Please help me figure out Thanks

                      P Offline
                      P Offline
                      PIEBALDconsult
                      wrote on last edited by
                      #10

                      A NumericUpDown already has everything you need.

                      1 Reply Last reply
                      0
                      • X Xonel

                        Hi This code here below allows only numbers and one decimal point to be typed on a textbox. It does not prevent you from: 1. Saving nulls in the database 2. From pasting any other character(words, asterisks,numbers etc) to the textbox. What do i have to add to the code to prevent the two problems from occurring?? Here is my code:

                            private void txtBalance\_TextChanged(object sender, EventArgs e)
                            {
                                txtBalance.KeyPress += new KeyPressEventHandler(numbercheck\_KeyPress);
                            }
                            private void numbercheck\_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;
                                }
                            }
                        

                        Please help me figure out Thanks

                        D Offline
                        D Offline
                        DaveyM69
                        wrote on last edited by
                        #11

                        My Simple Numeric TextBox[^] may be a good place to start. It doesn't do everything you require but could with a little effort.

                        Dave
                        Binging is like googling, it just feels dirtier. Please take your VB.NET out of our nice case sensitive forum. Astonish us. Be exceptional. (Pete O'Hanlon)
                        BTW, in software, hope and pray is not a viable strategy. (Luc Pattyn)

                        X 1 Reply Last reply
                        0
                        • D DaveyM69

                          My Simple Numeric TextBox[^] may be a good place to start. It doesn't do everything you require but could with a little effort.

                          Dave
                          Binging is like googling, it just feels dirtier. Please take your VB.NET out of our nice case sensitive forum. Astonish us. Be exceptional. (Pete O'Hanlon)
                          BTW, in software, hope and pray is not a viable strategy. (Luc Pattyn)

                          X Offline
                          X Offline
                          Xonel
                          wrote on last edited by
                          #12

                          Nop....This is not VB

                          D 1 Reply Last reply
                          0
                          • X Xonel

                            Nop....This is not VB

                            D Offline
                            D Offline
                            DaveyM69
                            wrote on last edited by
                            #13

                            And neither is the article/source - all C#!

                            Dave
                            Binging is like googling, it just feels dirtier. Please take your VB.NET out of our nice case sensitive forum. Astonish us. Be exceptional. (Pete O'Hanlon)
                            BTW, in software, hope and pray is not a viable strategy. (Luc Pattyn)

                            1 Reply Last reply
                            0
                            Reply
                            • Reply as topic
                            Log in to reply
                            • Oldest to Newest
                            • Newest to Oldest
                            • Most Votes


                            • Login

                            • Don't have an account? Register

                            • Login or register to search.
                            • First post
                              Last post
                            0
                            • Categories
                            • Recent
                            • Tags
                            • Popular
                            • World
                            • Users
                            • Groups