-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 ??
    – ochzhen
    Nov 28, 2020 at 3:53
  • Thanks, but how do I do that? Nov 28, 2020 at 3:57
  • Posted an answer, please check if it what you are looking for
    – ochzhen
    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

6
  • Thanks, but I'm getting CS1503 error saying: Argument 1 cannot convert from char to string..... Nov 28, 2020 at 4:12
  • I've corrected the answer to use string instead of char, please try it out ;)
    – ochzhen
    Nov 28, 2020 at 4:14
  • Thank you very much! Seems to work smoothly now :-). Much appreciated. Nov 28, 2020 at 4:25
  • Welcome! I'll appreciate if you accept this answer :)
    – ochzhen
    Nov 28, 2020 at 4:27
  • Definitely the problem has been ccompletely solved. Nov 28, 2020 at 4:52

Not the answer you're looking for? Browse other questions tagged or ask your own question.