-3

Can someone explain how to use TryParse in C# Visual Studio to validate some textbox. I need a function using TryParse, I have an idea but it's not working

public void Letra(TextBox caja)
{
   char valor;

   if(char.TryParse(caja.Text, out valor))
   {
        if (caja.TextLength>1)
        {
            caja.Text = caja.Text.Remove(caja.TextLength);
            caja.SelectionStart = caja.TextLength;
        }
   }
}
Mark Seemann
  • 225,310
  • 48
  • 427
  • 736

3 Answers3

0

Please see the code below. Please note, using Javascript this could be done a lot better, but since you really want a C# function, here it is.

public bool isValid(TextBox caja)
           {
               string sTemp;
               if (caja != null)
               {
                   sTemp = caja.Text;
               }
               else
               {
                   return false;
               }

               if (sTemp.Length > 0)
               {
                   foreach (char cTemp in sTemp)
                   {
                       if (char.IsNumber(cTemp))
                       {
                           return false;
                       }
                   }
               }
               else
               {
                   return false;
               }
               return true;
           }

Regards

JP Roelofse
  • 158
  • 1
  • 7
  • var output = Regex.Replace(input, @"[\d-]", string.Empty); where input is your Textbox's text This will return the string for you containing only letters – JP Roelofse Oct 31 '13 at 06:21
0

You can always use Regular Expression for such type of validation. It is best practice and pretty fast-

Regex charOnly=new Regex("^[^0-9]$");

You can use it in C# as you want and if your TestBox is in web form then use RegularExpressionValidator. You should refer How can I get a regex to check that a string only contains alpha characters [a-z] or [A-Z]?

Community
  • 1
  • 1
ucguy
  • 91
  • 1
  • 2
0

You can check if your string contains numbers with following method

private bool CheckIfTextContainsNumber(string TextToCheck)
{
    return Regex.IsMatch(TextToCheck, @"\d");
}
  • \d stands for digit (0-9) + other digits e.g. arabic

Further you code create a textbox in which you cannot type in kind of numbers by creating an EventHandler which catches the KeyPress-Event.

YourTextBoxControl.KeyPress += YourTextBoxControl_KeyPress;

Here you can check whether the char typed in is a number. If the char is a number then you set Handled to true

private void YourTextBoxControl_KeyPress(object sender, KeyPressEventArgs e)
{
    e.Handled = Char.IsNumber(e.KeyChar);
}
Daniel Abou Chleih
  • 2,440
  • 2
  • 19
  • 31