0

I am building a program in C#. What I want to do is, "When I press search, if textbox one and textbox 2 contain only numbers, show search results".

How do I say, "if contains 0-9"?

My current method does not work. I tried Contains, but I want it to include all the numbers.

protected void Button1_Click(object sender, EventArgs e)
{
    if (TextBox1.Text != "0-9" && TextBox2.Text != "0-9")  
    {
        GridView1.Visible = true;
    }

    else  
    {
        Label3.Text = "Insert phone and id correctly:" ;
    }
}
Tetsuya Yamamoto
  • 24,297
  • 8
  • 39
  • 61
C Java
  • 446
  • 2
  • 16
  • You can try to convert as int if it true then phone is correct otherwise incorrect. Or you check contains value – Md. Abdul Alim Oct 31 '18 at 11:49
  • 1
    @Md.AbdulAlim A phone "number" could be too large for an int. – Andrew Morton Oct 31 '18 at 11:49
  • 1
    You are looking for a *Regular Expression* E.g. https://stackoverflow.com/questions/16373895/regular-expression-for-specific-number-of-digits – Alex K. Oct 31 '18 at 11:49
  • Something that can have significant leading zeros is not really a number & should never be treated as such. – Alex K. Oct 31 '18 at 11:51
  • Who voted to reopen and why? There are tons of possible duplicates. Suggest different ones if you don't agree and I'll add them. This is most definitely not a unique question. – CodeCaster Oct 31 '18 at 11:54

1 Answers1

1

You use Regex as an option. Something like this should works:

Regex pattern = new Regex(@"\+[0-9]{3}\s+[0-9]{3}\s+[0-9]{5}\s+[0-9]{3}");

if (pattern.IsMatch(TextBox1.Text))
{
     GridView1.Visible = true;
}
else  
{
   Label3.Text = "Insert phone and id correctly:" ;
}

As per your requirement, you can change this, so that it would be more close to your needs. For example this is another Regex:

@"^(\+[0-9]{9})$"

As an another solution, you can also use LINQ:

if (textBox1.Text.All(char.IsDigit))
{
    GridView1.Visible = true;
}

Just don't forget to add these to your using statements:

using System.Text.RegularExpressions;
using System.Linq;
Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
  • 1
    An int32 can't contain phone numbers of 12 digits (ignoring the 00 of the country prefix), and that regex is oddly specific. – CodeCaster Oct 31 '18 at 11:59
  • 1
    @CodeCaster Check my updated answer. Yes, that's specific and of course the OP can change it as per his requirements. – Salah Akbari Oct 31 '18 at 12:02