Get data of multiple datagridew c#

Asked by At
List<string> comments = new List<string>();
    List<string> words = new List<string>();
    foreach (DataGridViewRow k in dataGridView2.Rows)
            {
                if (k.Cells[1].Value == null)
                { }
                else 
                {
                string com= (k.Cells[1].Value.ToString());
                string[] comment = com.Split(' ');
                foreach (string w in comment)
                {
                    comments.Add(w);
                }
                }

                foreach (DataGridViewRow t in dataGridView1)
                {
                    if (t.Cells[0].Value == null || t.Cells[1].Value == null || t.Cells[2].Value == null)
                    { }
                    else
                    {
                        words.Add(k.Cells[0].Value.ToString());
                        string sys = (t.Cells[2].Value.ToString());
                        string[] ww = sys.Split('،');
                        foreach (string r in ww)
                        {
                            words.Add(r);
                        }
                    }
                    foreach (string c in comments)
                    {
                        foreach (string q in words)
                        {
                            if ((c == q) && (t.Cells[1].Value.ToString.Equal("2")))
                            {
                                MessageBox.Show("found and high rank ");
                            }

                        }
                    }
                }

when I run the code, the error appear in the following

Index was out of range. Must be non-negative and less than the size of the collection.

Where the wrong line is marked on the next line

 if (t.Cells[0].Value == null || t.Cells[1].Value == null || t.Cells[2].Value == null)

How can I fix my code? Thank in advance

1 Answers

0
Hasta Tamang On

Error 1: dataGridView1 was missing Rows and was rightly you got the compiler error.

foreach (DataGridViewRow t in dataGridView1.Rows)

Error 2: ToString was missing parenthesis and it is Equals to compare two Strings

 if ((c == q) && (t.Cells[1].Value.ToString().Equals("2")))