ammar
ammar

Reputation: 23

How to check if a textbox starts with numeric value

In Windows forms C#, I want to check if a textbox I made starts with a numeric value, then if it does I want to insert the minus (-) sign at the beginning to change the number to negative, I found a way but it's too time wasting, here's my code:

if (richTextBox1.Text.StartsWith("1") || richTextBox1.Text.StartsWith("2") #until richTextBox1.Text.StartsWith("9"))
{
    richTextBox1.Text.Insert(0, "-");
}

So I was asking, if there's a shorter way to replace that code?

Upvotes: 1

Views: 1068

Answers (4)

Yuriy Faktorovich
Yuriy Faktorovich

Reputation: 68707

if (Char.IsNumber(richTextBox1.Text[0]))...

You should also add some checks around it to make sure there's text.

Upvotes: 5

Trevor
Trevor

Reputation: 8004

Many good answer's already here, another alternative is if you want culture support give this a try...

 public static bool IsNumber(char character)
 {
    try
    {
       int.Parse(character.ToString(), CultureInfo.CurrentCulture);
       return true;
    }
       catch (FormatException) { return false; }
 }

You can call it like:

 if ( IsNumber(richTextBox1.Text[0]))

Upvotes: -1

Gopinath
Gopinath

Reputation: 4957

Checking if the first character of a text is a number can be done in single line, using Char.IsNumber() function as follows:

if ( Char.IsNumber( stringInput, 0) ) {

 // String input begins with a number

}

More information: https://learn.microsoft.com/en-us/dotnet/api/system.char.isnumber

Upvotes: 0

Johnathan Barclay
Johnathan Barclay

Reputation: 20373

Using regex:

if (Regex.IsMatch(richTextBox1.Text, @"^\d"))

Matches a digit (0-9) at the start of the string.

Or a direct replace:

richTextBox1.Text = Regex.Replace(richTextBox1.Text, @"^\d", "-$&");

Upvotes: 0

Related Questions