3

I'm currently working on an IRC bot. The sent messages will be shown in a DataGridView. So now I want to check if for example the sent message contains a specific word. Let's say "test".

So it should check for the following:

Let's say the sent message, which is added to the DataGridView is: My name is test.

Now the Cell, which contains the word "test" should get colored red.

I already solved this, when the message ONLY contains "test". But I don't really know how to check for a word in a sentence.

//Edit: I tried this code:

foreach (DataGridViewRow row in dataGridView1.Rows)
{
      if (row.Cells[1].Value.ToString() == "test")
          row.Cells["chat1"].Style.ForeColor = Color.Red;
          //row.Cells["chat1"].Style.ForeColor = Color.CadetBlue;
}

Kind Regards, Max :)

2
  • 2
    please post your code what you tried so that we can help with you; As a matter of fact, you can test your yourStringVariable.Contains(stringToCheck)
    – techspider
    Apr 25, 2016 at 18:11
  • Thanks for your answer. I added my code in the question :) Apr 25, 2016 at 18:16

2 Answers 2

8

Check with Contains to verify the string presence anywhere in the given input. You may consider to apply ToLower or ToUpper methods before checking Contains to ensure proper results

foreach (DataGridViewRow row in dataGridView1.Rows)
{
     if (row.Cells[1].Value.ToString().Contains("test"))
        row.Cells["chat1"].Style.ForeColor = Color.Red;
        //row.Cells["chat1"].Style.ForeColor = Color.CadetBlue;
}
1
  • Oh god.. What an easy fix.. I think this was a brain error on my side haha.. Thanks for your help! :) Apr 25, 2016 at 18:19
3

you can also practice using linq to solve this problem

 var items = this.dataGridView1.Rows.Cast<DataGridViewRow>()
             .Where(row => row.Cells[1].Value.ToString() == "Test");

 foreach(DataGridViewRow row in items)
 {
      row.Cells["chat1"].Style.ForeColor = Color.Red;
 }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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