简体   繁体   中英

TextBox text format in C#

I want something like this 01 or 02 or 03 but not 00 in my textbox ie both the digits allowed in the textbox should not be 0.

Again clearly I don't want first 0 followed by second 0 in textbox. So do anyone has got idea?

In your format string (when you call ToString) you can use a ; character to define a "zero" format like this:

myTextBox.Text = myNumber.ToString("00;;Something");

MSDN Custom Numeric Formatting: Semicolon Separator

if the content of your text box value is integer, cause it's not clear form your quesiton, can use something like this:

public string GetFormattedString(int iValue) {
    if(iValue!=0)
      return iValue.ToString("00");

    return string.Empty;
}

This returns '01', for example, and for 0 returns "".

If it's not ok, please explain better what you actually need.

Regards.

您可能还想尝试MaskedTextBox吗?

Don´t know if you mean it so. But you can use the TextChanged Event.

  private void textBox1_TextChanged(object sender, EventArgs e)
  {
     if (textBox1.Text == "00")
     {
        textBox1.Text = "";
     }
  }

If the Text in the Textbox changed, you can check if the Text is "00". Then you can handle it, in my example the Textbox is empty again.

Hope that I understand you right and could help you.

if you want to validate input text from textbox control you can use the Regex in your case it will be like this

        string strRegex = @"^\d[1-9]$";
        Regex myRegex = new Regex(strRegex);
        string strTargetString = @"03"; // put here value from text box
        if (myRegex.IsMatch(strTargetString))
        {
            MessageBox.Show("Correct");
        }
        else
        {
            MessageBox.Show("Incorrect input");
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM