Pravin Chopade
Pravin Chopade

Reputation: 77

How to find cells having same values in DataGridView?

I have DataGridView containing number of rows and columns, like ID, Name, Addr, etc. I want to find rows which have same value in the Name column. e.g.

ID     Name     Addr
----------------------
1    Pravin     India
2    Shubham    Nepal
3    Pravin     Bhutan

Now I wanted to get ID 1 & 3 based on same cell value.

Upvotes: 0

Views: 1719

Answers (1)

TaW
TaW

Reputation: 54433

Many ways to do this..

You could sort the DataGridView by name and then iterate over it to look for duplicate names.

Or you could read the data into a Dictionary like this:

    Dictionary<string, List<int>> data = new Dictionary<string,List<int>>();

    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        string name = row.Cells[1].ToString();
        int ID =  Convert.ToInt32(row.Cells[0]);
        if (data.ContainsKey(name)) data[name].Add(ID);
        else data.Add(name, new List<int>(new int[] { ID }));
    }

    foreach (string name in data.Keys)
        if (data[name].Count > 1 ) 
        {
            Console.Write(name);
            foreach (int ID in data[name]) Console.Write(ID.ToString("##### "));
            Console.WriteLine();
        }

Or you could wait for someone with a cute LINQ solution..

Upvotes: 1

Related Questions