0

I am having a problem here. I am trying to display how many times each one of the strings in datagridview column "Values" appear. I am trying to display each occurrence next to each value(for example I want this: 71->4, 83 ->7 , 0B->6 etc.). Here is my code. I'm only taking as a result the first one. Thanks in advance.

    private void button4_Click(object sender, EventArgs e)
    {
        string Text = richTextBox1.Text;

        string[] words = Text.Split(' ');
        foreach (string word in words)
        {
            dataGridView1.Rows.Add(word);
        }

        string searchTerm = " " ;
        foreach (DataGridViewRow r in dataGridView1.Rows )
        {
            if (searchTerm == null || searchTerm == String.Empty || searchTerm.Trim().Length == 0)
            {
                searchTerm = r.Cells["Value_Detected"].Value.ToString();

                var matchQuery = from wor in words
                                 where wor.ToUpperInvariant() == searchTerm.ToUpperInvariant()
                                 select wor;


                int wordCount = matchQuery.Count();

                r.Cells["Occur"].Value = wordCount.ToString();
            }


        }




        button4.Enabled = false;
    }
  • What is that "if" condition in the loop for? That makes the block runs only once. – Mehrzad Chehraz Apr 25 '15 at 17:24
  • If i dont use the "if" error occurs for NullException... do you know a way that i can transform this so as to have the result i want? I am totally new at programming so any help will be just perfect – Perkoules Apr 26 '15 at 17:55
  • That "if" makes no sense. What line throws null refrerence exception? If it is the line you get value from the cell, you need to check value is not null before calling .ToString method on it. – Mehrzad Chehraz Apr 26 '15 at 18:00

1 Answers1

0

Instead of

if (searchTerm == null || searchTerm == String.Empty || searchTerm.Trim().Length == 0)

it should be :

if (r.Cells["Value_Detected"].Value != null)