Search code examples
c#datagridviewcolorscontains

C# Check if DataGridView Contains specific word


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


Solution

  • 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;
    }