2

I don't have idea How can I search word for a sentence in C#. In case the word is anywhere in the sentence.

My plan is if have the word that I set up in anywhere the sentence the button1 will visible.

e.g. => I set up the word is 'ABC' in label1.

if the sentence in textbox1 is : I'am ABC. or : ABC is here. or : The ABC is come. or : 12345ABCDEFG

The Button1 will visible.

I tried coding :

string textToSearchFor = "ABC";
int index = textbox1.Text.IndexOf(textToSearchFor, StringComparison.OrdinalIgnoreCase);
if (index >= 0)
{
    button1.Visible = true;
}
else
{
    button1.Visible = false;
}

but It didn’t go as planned.

-Edited-

Because When in textbox1 value is ABC then button1.Visible is true

But when textbox1 value is ABC is here. or The ABC is come. then button1.Visible is false

Please anyone help me how? Thank you.

Meawmill
  • 67
  • 1
  • 13
  • 2
    What didn't go to plan? The string check looks like it should work as you intended. – Ted Apr 24 '20 at 10:06
  • https://stackoverflow.com/questions/10709821/find-text-in-string-with-c-sharp – Serban Gorcea Apr 24 '20 at 10:07
  • 1
    You "tried coding", but *where* did you put the code? Are you sure it is getting called when you expect it to? Can you put a breakpoint in the code and see if you hit it? – Hans Kesting Apr 24 '20 at 10:19

1 Answers1

6

It's unclear what "didn't go as planned" really means but you have a much cleaner option available to you. We're going to use the Contains extension method.

button1.Visible = textbox1.Text.Contains("ABC");

You haven't really specified where you're trying to run this code from but if it's on a timer's event, or something similar, this will effectively bind the button's visibility to the boolean result of the Contains method.

Do note: this isn't case insensitive; I'd call that a different topic ... probably.

clarkitect
  • 1,720
  • 14
  • 23
  • Thank you so much! It's very easy <3 and I edited my question what "didn't go as planned" I think everybody will understand me. – Meawmill Apr 27 '20 at 01:54