Home > front end >  Check if 2 textboxes have the same data type
Check if 2 textboxes have the same data type

Time:01-30

I am trying to make a Kinematics Calculator on C#, you input 3 numerical values, a letter and a question mark (each in different text boxes). The letters change depend on the value you are inputting. For example, you would input "A" for acceleration but "T" for time. Unfortunately, the problem is I need a function that finds if 2 letters are present in 2 different text boxes and display a message box saying you cannot do that, etc

For example,

If I had a textbox that had a user input of "A" and another textbox that had a user input of "T", then I need a message box that outputs "Only 1 letter allowed, please try again".

Is there a way to do this?

CodePudding user response:

You can use Char.IsLetter() method alongside the LINQ Any()to achieve that. Char.IsLetter() method will return true if the provided char is an uppercase or lowercase letter. Note that if any of the chars of the string is a letter, the expression return will return true, if you need to check if all the characters of the string are a letter, use .All() instead of .Any()

string textbox1Value = "V";
string textbox2Value = "T";
bool hasTwoLetters = textbox1Value.Any(x => char.IsLetter(x)) &&  textbox2Value.Any(x => char.IsLetter(x));
Console.WriteLine(hasTwoLetters);
if(hasTwoLetters)
{
    // Display alert
}

CodePudding user response:

You could do a "tryParse" on each text field. If it fails you know there is a character present. You then count the amount of "fails". There are many different ways to detect how many alpha characters there are. You may need to strip the "?" field with .Replace("?","") too.

int parsedValue = 0;
int lettersPresent = 0;

if (!int.TryParse(textBox1.Text, out parsedValue)) lettersPresent  ;
if(!int.TryParse(textBox2.Text, out parsedValue)) lettersPresent  ;

if (lettersPresent > 1) MessageBox.Show("Only 1 letter allowed, please try again");

It may be easier to just combine the textbox values and check with contains as well:

string combined = textBox1.Text   textBox2.Text;
int letterCount = 0;

if (combined.Contains("T")) letterCount  ;
if (combined.Contains("S")) letterCount  ;

if (letterCount > 1) MessageBox.Show("Too many..");

I am assuming you are parsing the letters out at some point so it probably should just be included inside that method.

  •  Tags:  
  • Related