locked
How to format textbox

    Question

  • Hi guys,

    Greetings!

    Would it be possible to format the textbox in such a way user can only enter numeric data including one period ?

    Just like in Visual FoxPro? Where the textbox can be pre-formatted during design time such that when user types in, numerals and period are the only valid character that user can only enter.

    Is this possible? If yes on any how, please help.

     

    Thanks,

     

    Monday, October 16, 2006 7:49 AM

Answers

  • you could also use the keypress events of a textbox and check to see if its numeric, if not, handle it. Example:

    //implement the keypress event of the textbox - click textbox, go to its properties in designer view, click on event (the lightning symbol) and double click keypress to create the event

    Then the code....

     

    if (!Char.IsNumber(e.KeyChar) && !Char.IsControl(e.KeyChar))

    {

       e.Handled = true;

    }

     

    this allows only numbers to be entered and any control keys (such as the backspace/delete key)

    Monday, October 16, 2006 10:41 AM

All replies

  • Hi,

    The .NET framework comes with a MaskedTextBox control. This is acutally nothing more than a TextBox with some added fuctionality. I assume the functionality will be more or less the same as in Visual FoxPro.

    You can read about here:: http://msdn2.microsoft.com/en-us/library/system.windows.forms.maskedtextbox.aspx

    Hope this helps,

     

    Monday, October 16, 2006 8:36 AM
  • you could also use the keypress events of a textbox and check to see if its numeric, if not, handle it. Example:

    //implement the keypress event of the textbox - click textbox, go to its properties in designer view, click on event (the lightning symbol) and double click keypress to create the event

    Then the code....

     

    if (!Char.IsNumber(e.KeyChar) && !Char.IsControl(e.KeyChar))

    {

       e.Handled = true;

    }

     

    this allows only numbers to be entered and any control keys (such as the backspace/delete key)

    Monday, October 16, 2006 10:41 AM
  • Hi  ahmedilyas,

    Thank you for the reply. I'm wondering how can we have the period be included because this will be a price field.

    Finally, how about automatically separating thousands with a comma? I mean as the user types in 1000 it will be automatically be 1,000.00? Will this be possible in keypress?

    Or will it be more pratical to use the MaskedTextBox as suggested by sir Sven De Bont?

    Thank you ahmedilyas and Sven De Bont, for the answer. Hope you could still help me to work on these.

    Thanks,

     

    Tuesday, October 17, 2006 12:26 AM
  • for this, most likely the best way would be to use the initial suggestion provided by Sven - the MaskedTextBox
    Tuesday, October 17, 2006 12:45 AM
  • Hi ahmedilyas,

    Thank you!

    Another question, if MaskedTextBox is possible for textbox entry, how about if I want it in my DataGridView like I have a column there that user can enter the number of items purchase (I prefer to have number separated with comma) just like the validation on my first question : )

    Thanks again!

    Tuesday, October 17, 2006 1:12 AM
  • Hi guys,

    Big proble, I just tried the MaskedTextBox, I tried to format it like this 99,999,99.00 so run it, then I want to enter this value to my maskedtextbox 150.00, what happen is this 150,____,___.00

    First of it looks like 150,000,000.00

    Secondly, is there any way I can type 150 then press the period then my cursor go to the last two digits?

    Lastly, I have my datagridview control where records were posted, the problem is the maskedtextbox can display it properly, instead of displaying 400.00 it displays 400,000,000.00.

     

    Please guide me.

     

    Thanks,

     

    Tuesday, October 17, 2006 2:58 AM
  • Hi,

    extending an earlier solution  use the line below -

    if (!Char.IsNumber(e.KeyChar) && !Char.IsControl(e.KeyChar)&& !((char)('.')==(e.KeyChar)))

    which will allow a number of decimal points. and I expect you may want a '+' and a '-' maybe an 'e', or 'E' or currency sign - same principle. However if you want to restrict it to one decimal point, then set up a counter, and switch if statements. At the moment I'm parsing numeric fields after they are completed, which is not ideal, imnsho. I will persue this idea.

     But then, you got to keep track of it, in case you go back to the text box and edit it... Its a pity the masked text box is so useless

    Best wishes,

    Ray

    Wednesday, October 18, 2006 7:16 PM
  • Well, I think the following does it. Probably not the smartest way, but seems to work. Any improvements offered?

     

    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)

    {

    if (this.textBox1.Text.Length == 0) return;

    if (this.textBox1.Text[0] == '+')

    {

             if ((char)('+') == (e.KeyChar)) return;

    }

    if (this.textBox1.Text[0] == '-')

    {

            if ((char)('-') == (e.KeyChar)) return;

    }

    if (this.textBox1.Text.IndexOf('.', 0) == -1)

    {

         if ((char)('.') == (e.KeyChar)) return;

    }

    if (!Char.IsNumber(e.KeyChar) && !Char.IsControl(e.KeyChar))

    {

          e.Handled = true;

    }

    }

     

     

    Wednesday, October 18, 2006 8:43 PM
  • The previous one never handled the + or - correctly, this version is better (refactored  tb is the textBox1.Text)

    private void decimalcheck(string tb, KeyPressEventArgs e)

    {

    if (tb.Length == 0)

    {

    if ((char)('+') == (e.KeyChar)) return;

    if ((char)('-') == (e.KeyChar)) return;

    }

    if (tb.IndexOf('.', 0) == -1)

    {

    if ((char)('.') == (e.KeyChar)) return;

    }

    if (!Char.IsNumber(e.KeyChar) && !Char.IsControl(e.KeyChar))

    {

    e.Handled = true;

    }

    }

    I'm leaving it there ;-) , before I find some other bug

     Best wishes,

    Ray

    Wednesday, October 18, 2006 9:29 PM
  • If your own post solved your problem, could you mark it as 'answer'. This makes the thread appears as 'answered' to other users.

    Thanks,

    Saturday, October 21, 2006 6:50 AM
  • Hi guys,

    I tried modifying the code for my datagridview textbox column, I want to enable the period "." but only once. Like 1.50, but not 1....50  or  0.20.20

    Here's the modified code,

    private void myTextBoxInventoryIn_KeyPress(object sender, KeyPressEventArgs e)

    {

    if (this.dataGridViewInventoryIn.CurrentCell.ColumnIndex == 0)

    {

    if(sender.ToString().IndexOf('.',0) == -1)

    {

    if ((char)('.') == (e.KeyChar))

    {

    return;

    }

    }

    }

    if (!Char.IsNumber(e.KeyChar) && !Char.IsControl(e.KeyChar))

    {

    e.Handled = true;

    }

     

    }

    Thanks guys!

     

    Regards,

     

     

    Monday, January 01, 2007 2:48 PM
  • This will work.  It allows only one decimal point.  A minus sign may be placed as the leftmost character.  The backspace key can be used to delete any characters.

             private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
             {
                    bool dot = false;
                    bool flag = false;
                    if (e.KeyChar == '\b') return;
                    if (e.KeyChar == '.' & textBox1.Text.IndexOf('.') > 0) dot = true;
                    if (e.KeyChar < '-' | e.KeyChar > '9' | dot == true) flag = true;
                    if (textBox1.Text.Length > 0 & e.KeyChar == '-') flag = true;
                    if (e.KeyChar == '/') flag = true;
                    if (flag == true) e.Handled = true;
             }

     

    Monday, January 01, 2007 6:59 PM
  • Hi Solitaire,

    Thank you for the reply. However, I cant make the . to work, I'm not so sure why there's textBox1? What I used is the object sender like

    sender.ToString().IndexOf('.') > 0

    Here's the parent which calls the even KeyPress, I used the EditingControlShowing event of DataGridView control

    private void dataGridViewInventoryIn_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)

    {

    int columnIndex = dataGridViewInventoryIn.CurrentCell.ColumnIndex;

    if (columnIndex == 0)

    {

    // create a textbox and create keypress event

    TextBox myTextBox = e.Control as TextBox;

    myTextBox.KeyPress += new KeyPressEventHandler(this.myTextBoxInventoryIn_KeyPress);

    }

    else if (columnIndex == 1)

    {

    // create combobox and create keypress event

    ComboBox myComboBox = e.Control as ComboBox;

    myComboBox.SelectedIndexChanged += new EventHandler(this.myComboBoxInventoryIn_SelectedIndexChanged);

    }

      

    }

    Now how can I change the textBox1 in your code? Thanks!

     

    Your code:

     private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
             {
                    bool dot = false;
                    bool flag = false;
                    if (e.KeyChar == '\b') return;
                    if (e.KeyChar == '.' & textBox1.Text.IndexOf('.') > 0) dot = true;
                    if (e.KeyChar < '-' | e.KeyChar > '9' | dot == true) flag = true;
                    if (textBox1.Text.Length > 0 & e.KeyChar == '-') flag = true;
                    if (e.KeyChar == '/') flag = true;
                    if (flag == true) e.Handled = true;
             }

     

    Tuesday, January 02, 2007 2:19 PM
  • My code works with a plain vanilla textbox.  I don't know how it would fit in with a datagrid or combobox.  Maybe someone else can take it from here.

     

    Tuesday, January 02, 2007 11:36 PM
  • Hi, Beast

    Put the code in myTextBoxInventoryIn_KeyPress method as you have defined a KeyPress event, just as follows:

    private void myTextBoxInventoryIn_KeyPress (object sender, KeyPressEventArgs e)
    {

    //your code here

    }
    Thanks

    Wednesday, January 03, 2007 2:56 AM
  • Can someone help me? Please....

     

    Thanks guys!

    Wednesday, January 03, 2007 2:58 AM
  • Hi,

    this is put in form1, so I know where it is ;-)
     

      public static void dc(string tb, KeyPressEventArgs e)
              {
              if (tb.Length == 0)
                  {
                  if ((char)('+') == (e.KeyChar)) return;
                  if ((char)('-') == (e.KeyChar)) return;
                  }
              if (tb.IndexOf('.', 0) == -1)
                  {
                  if ((char)('.') == (e.KeyChar)) return;
                  }
              if (!Char.IsNumber(e.KeyChar) && !Char.IsControl(e.KeyChar))
                  {
                  e.Handled = true;
                  }
              }
      

    then whenever I want to check a textbox is numeric, then it is called when required, when a keypress occurs in a text box, as below,

         private void textBox_KeyPress(object sender, KeyPressEventArgs e)
            {
                string astring,bstring;
                astring = "";
                bstring = "";
                // check for drill size as text

                if (this.label7.Text == "Drill Size")
                    {
                    if (this.textBox7.Focused == true) return;
                    }
                if (this.label5.Text == "Drill Size")
                    {
                    if (this.textBox5.Focused == true) return;
                    }
                if (this.Text == "Engrave")
                    {
                    if (this.textBox7.Focused == true) return;
                    }

              astring = sender.ToString();
             
           
              bstring = astring.Substring(36);
                Form1.dc( bstring,e);
            }


    You need to check the form designer has something like

    this.textBox7.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.textBox_KeyPress);

    for each required textbox

    You get that by setting the properties for each textbox  (under 'Key').

     


    This is how it works -

    the keyPress event is raised when a key press occurs - OK so far?

    this fires up the textBox_KeyPress code

    ignore all of that code, until the last few lines (it does different things if other text box types are selected.) so for the numeric textboxes, it sends a string starting from position 36 of the textbox keypress sender to the dc method described a few months ago, and shown at the top of here.

    Now, there are plenty of improvements that can be made, Do what you wish with it. The most significant problem? is that the textBox is not passed by reference, so it is not possible to alter the textbox, only add characters (characters can be delete or backspace). This means, that in order to change a + to -, the whole field has to be deleted. It is not a problem to me or my application. It may be simpler to pass the current location of the character being 'keypressed'. Then check if its in the first position to allow a + or -. At the moment, it is only possible to enter a + or - if it is the first and only entry.

    I have deliberately not explained it too well, trying to teach you how to fish, not give you fish, and I'm too lazy, too.

    This is a fairly general solution, can be applied to other fields, afaik. If you only have a couple of text boxes or whatevers, then maybe do a more specific solution, as shown by others. (solitaire recently)

    Have a good year,

    Best wishes,

    Ray

    Wednesday, January 03, 2007 4:10 PM
  • Hi Ray and Figo Fie,

    Have you tried this with the datagridview textbox? Bec my issue is on that control, not the pure plain textbox control, its from the datagridview...

     

    Thanks all for the answers, please keep on helping...

    Saturday, January 06, 2007 2:56 AM
  • My reply was to your original query - you just referred to a text box. I suggest you do a simple test project textbox thing, and try the examples given, to get to grips with how the examples given work. Then drop in a datagrid view, and try altering the examples to work with that. I have never used the datagridview, but assuming an event is raised when a key is pressed, and assuming it uses text strings, then I think all you need do is ensure the correct string is selected for parsing. I guess that string will be somewhere within the object sender. Try things for yourself, see what happens. Use debug, break points, etc. search the help text, try different examples. It may take a day or two of thrashing around in frustration, but, such is life...

    Best wishes,

    Ray

    Saturday, January 06, 2007 1:20 PM
  • Hi Ray,

     

    Thanks for the advice. I'll take it from here.

     

    Regards,

     

    • Proposed as answer by AmooReza Friday, February 19, 2010 5:59 PM
    Saturday, January 06, 2007 2:25 PM
  •  Beast Forever

    how do you resolved?? I'm in the same situation :(

     

    Thanks

    Tuesday, February 06, 2007 8:39 AM
  • try it;
    textbox.text = string.Fromat("c" , sth);
    Friday, February 19, 2010 6:00 PM
  • check this page out, this code worked for me on validating if an email address has been entered correctly in a textbox in C# (for .NET 4).

    http://msdn.microsoft.com/en-us/library/system.configuration.regexstringvalidator.aspx

     

    Thursday, August 26, 2010 1:11 PM