Prashiddha Raj Joshi
Prashiddha Raj Joshi

Reputation: 91

TextBox text format in C#

I want something like this 01 or 02 or 03 but not 00 in my textbox i.e. 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?

Upvotes: 1

Views: 8128

Answers (5)

Sergey K
Sergey K

Reputation: 4114

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");
        }

Upvotes: 0

Andre Gross
Andre Gross

Reputation: 263

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.

Upvotes: 1

Spence
Spence

Reputation: 29360

You might want to try a MaskedTextBox as well?

Upvotes: 1

Eric Falsken
Eric Falsken

Reputation: 4932

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

Upvotes: 6

Tigran
Tigran

Reputation: 62265

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.

Upvotes: 1

Related Questions