Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to compare cells of one column for selected rows?

Hi everyone please i need you’re help if it’s possible:
i have a DGV with 8 columns i want to compare all cells of second column "Fournisseur" whene rows are selected.

  • image1: selected rows have the same value of second column "Tramauto"="Tramauto"
  • image2: selected rows have differents values of sec column 1row "Tramauto"= 3row "Tramauto" but 2row different "Sonasid"

If=True

If=False

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

private void button13_Click(object sender, EventArgs e)
    {
      foreach (DataGridViewRow row in commandeDataGridView.SelectedRows)
            {
                 if(//selected rows have the same value of second column)
                    {do function}

               else
            {

                string message = "shoose the same Fournisseur";
                string title = "Error";
                MessageBox.Show(message,title);
            }

Thank you so much for you’re help!

>Solution :

You could use:

List<string> allCol2Values = commandeDataGridView.SelectedRows.Cast<DataGridViewRow>()
    .Select(r => r.Cells[1].Value?.ToString())
    .ToList();
string first = allCol2Values.FirstOrDefault();
bool allSame = allCol2Values.Skip(1).All(s => s == first);

If you don’t want to use LINQ, this is the classic loop way:

bool allSame = true;
string firstValue = null;
foreach (DataGridViewRow row in commandeDataGridView.SelectedRows)
{
    string col2Value = row.Cells[1].Value?.ToString();
    if (firstValue == null) firstValue = col2Value;
    if(col2Value != firstValue)
    {
        allSame = false;
        break;
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading