Compare Cell Content in DataGridView

Posted on 2008-11-04
Last Modified: 2013-12-17
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.
Question by:MichelleLacy
    LVL 6

    Accepted Solution

    Hello MichelleLacy,

    try this code

    private bool areCellsSame()
                bool allTheSame = true;


                    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;



    Author Closing Comment

    works wonderfully!!!

    Featured Post

    How to run any project with ease

    Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
    - Combine task lists, docs, spreadsheets, and chat in one
    - View and edit from mobile/offline
    - Cut down on emails

    Join & Write a Comment

    More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
    Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
    This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor ( If you're looking for how to monitor bandwidth using netflow or packet s…
    In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor ( If you're interested in additional methods for monitoring bandwidt…

    755 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    17 Experts available now in Live!

    Get 1:1 Help Now