Compare Cell Content in DataGridView

I have a data grid view that uses a data table as its data source.  I want to add an if statement condition in my code that ensures that all of the  cell values in Column2 are the same.  If they are not the same, I want to disable one of the radio buttons on the form.  So essentially I was looking for a string comparison statement that compared all the cells in Column2 to the value of the 1st row in Column2 using a foreach statement.  I would like to see an example.
MichelleLacyAsked:
Who is Participating?
 
xRalfConnect With a Mentor Commented:
Hello MichelleLacy,

try this code

private bool areCellsSame()
        {
            bool allTheSame = true;

            try
            {

                string firstCell = dataGridView1.Rows[0].Cells[1].Value.ToString();

                foreach (DataGridViewRow dgvr in dataGridView1.Rows)
                {
                    string cellToCompare = dgvr.Cells[1].Value.ToString();

                    if (string.Compare(firstCell, cellToCompare, true) != 0)
                    {
                        allTheSame = false;
                        return allTheSame;
                    }

                }
            }
            catch (NullReferenceException)
            {
                return allTheSame;
            }

           
            return true;
        }


Regards,

xRalf
0
 
MichelleLacyAuthor Commented:
works wonderfully!!!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.