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 :)

Ramgy Borja
  • 2,330
  • 2
  • 19
  • 40
GERIskillzZz
  • 33
  • 1
  • 1
  • 4

2 Answers2

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;
}
Ramgy Borja
  • 2,330
  • 2
  • 19
  • 40
techspider
  • 3,370
  • 13
  • 37
  • 61
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;
 }
Ramgy Borja
  • 2,330
  • 2
  • 19
  • 40