Compare Cell Content in DataGridView

Posted on 2008-11-04
Medium Priority
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

Accepted Solution

xRalf earned 2000 total points
ID: 22876966
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

ID: 31513075
works wonderfully!!!

Featured Post

Restore individual SQL databases with ease

Veeam Explorer for Microsoft SQL Server delivers an easy-to-use, wizard-driven interface for restoring your databases from a backup. No expert SQL background required. Web interface provides a complete view of all available SQL databases to simplify the recovery of lost database

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Hello there! As a developer I have modified and refactored the unit tests which was written by fellow developers in the past. On the course, I have gone through various misconceptions and technical challenges when it comes to implementation. I would…
this video summaries big data hadoop online training demo (http://onlineitguru.com/big-data-hadoop-online-training-placement.html) , and covers basics in big data hadoop .
Are you ready to place your question in front of subject-matter experts for more timely responses? With the release of Priority Question, Premium Members, Team Accounts and Qualified Experts can now identify the emergent level of their issue, signal…
Suggested Courses

850 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