-1

This has been asked before in VB (apparently not satisfactory) but not in C#.

I need to add two punctuation marks to my String.Contains method (apart from the already existing "."), namely "!" and "?".

The idea is that the user finishes his/her input with a punctuation mark (i.e period, question mark or exclamation point). If they don't, the input will not be accepted in the text box.

 private void textBox1_TextChanged_1(object sender, EventArgs e)
        {
            
            if (textBox1.Text.Contains("."))
                
            {            
               Task.Delay(200).Wait();
                MessageBox.Show("Thanks for your input!");
            }

            else
            {
                return;
            }

How do I add these two? It seems impossible to add them as separate values...

3
  • If textBox1.Text is string type, why not just check if last char is . or ! or ?? Commented Nov 28, 2020 at 3:53
  • Thanks, but how do I do that? Commented Nov 28, 2020 at 3:57
  • Posted an answer, please check if it what you are looking for Commented Nov 28, 2020 at 4:04

1 Answer 1

1

If we need to only check the last character, we can do this using EndsWith method:

private void textBox1_TextChanged_1(object sender, EventArgs e)
{
    var text = textBox1.Text;
    if (text.EndsWith(".") || text.EndsWith("!") || text.EndsWith("?"))
    {            
         Task.Delay(200).Wait();
         MessageBox.Show("Thanks for your input!");
    }
    else
    {
         return;
    }
}

https://learn.microsoft.com/en-us/dotnet/api/system.string.endswith?view=netcore-3.1

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks, but I'm getting CS1503 error saying: Argument 1 cannot convert from char to string.....
I've corrected the answer to use string instead of char, please try it out ;)
Thank you very much! Seems to work smoothly now :-). Much appreciated.
Welcome! I'll appreciate if you accept this answer :)
Definitely the problem has been ccompletely solved.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.