Click here to Skip to main content
15,040,212 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi all, i have winform c# 2012
i have defined a datagridview in which there is a values. My datagridview has 2 columns (GREEN and RED ) and looks as follow:
------------------------
GREEN | RED | //headers of daatagridview
-----------------------
A | B |
-----------------------
C | A |
-----------------------
D | D |
-----------------------
E | Z |
-----------------------
E | Z |
-----------------------
what i want to do is to arrange the datagridview such that
-every item that appears in both columns is removed from GREEN column
-every item that appears more than one time in a same column, only one is kept ,the rest of duplicates is removed (ie: duplicate data in the same column are removed)

so the above datagridview should become after transformation like this:
------------------------
GREEN | RED | //headers of daatagridview
-----------------------
E | B |
-----------------------
C | A |
-----------------------
E | D |
-----------------------
| Z |
------------------------

what i have tried does work
how can i do it?
thanks in advance

What I have tried:

C#
List<string> list = new List<string>();
           
          
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
              
                if (dataGridView1.Rows[i].Cells[0].Value != null)
               {
                   string str_green = dataGridView1.Rows[i].Cells[0].Value.ToString();
                  if (!list.Contains(str_green))
                  {
                       list.Add(str_green);
                    }
                    else
                    {
                       dataGridView1.Rows.Remove(dataGridView1.Rows[i]);
                       
                   }
                }
               if (dataGridView1.Rows[i].Cells[1].Value != null)
               {
                 string str_red = dataGridView1.Rows[i].Cells[1].Value.ToString();
                    if (!list.Contains(str_red))
                    {
                       list.Add(str_red);

                    }
                    else
                    {
                        dataGridView1.Rows.Remove(dataGridView1.Rows[i]);
                       
                   }
                }
               
            //}
Posted
Updated 27-Mar-16 5:28am
v2

1 solution

Going back to my solution to your earlier question at How to add data in a specific cell from specific column[^] ...
These are issues I would address before populating the datagridview - in fact I would probably address the problems as I was populating the original DataTable.

So the adjustment to the solution on the other post is this (or similar)
C#
//get the "red" items first (because if they appear in both we don't want them in the green list)
var redItems = (dt.AsEnumerable().Where(x => x.Field<string>("Flag_created") == "Red")
    .Select(x => x.Field<string>("Society_Id"))).Distinct().ToList();
int r = redItems.Count();

//Get the "green" items
var greenItems = (dt.AsEnumerable()
    .Where(x => x.Field<string>("Flag_created") == "Green")
    .Select(x => x.Field<string>("Society_Id"))).Except(redItems).Distinct().ToList();
int g = greenItems.Count();

// Whichever is the greater count of items, add that many rows to the grid
dataGridView1.Rows.Add(Math.Max(g, r));

for (var i = 0; i < dataGridView1.Rows.Count; i++)
{
    if (i < greenItems.Count)
        dataGridView1.Rows[i].Cells[greenColumn].Value = greenItems[i];
    if (i < redItems.Count)
        dataGridView1.Rows[i].Cells[redColumn].Value = redItems[i];
}

Things to note:
- redItems and greenItems are now List<string> not List<datagridviewrow>
- I get the redItems first because I want to exclude any of those from the greenItems - see the .Except[^]
- I only want unique values so note the .Distinct[^]
- Also note the difference to how I'm populating the dataGridView from my previous solution (because the list items are now strings)

For completeness, if you already have a DataGridView populated you can convert the columns into Lists to do this manipulation later ... I created a button to remove the duplicates like this
C#
private void removeDups_Click(object sender, EventArgs e)
{

    var redList = dataGridView1.Rows
         .OfType<DataGridViewRow>()
         .Where(x => x.Cells[redColumn].Value != null)
         .Select(x => x.Cells[redColumn].Value.ToString())
         .Distinct()
         .ToList();

    var greenList = (from DataGridViewRow dr in dataGridView1.Rows
                     where dr.Cells[greenColumn].Value != null
                     select dr.Cells[greenColumn].Value.ToString()).Distinct().Except(redList).ToList();

    dataGridView1.Rows.Clear();
    dataGridView1.Rows.Add(Math.Max(greenList.Count(), redList.Count()));

    for (var i = 0; i < dataGridView1.Rows.Count; i++)
    {
        if (i < greenList.Count)
            dataGridView1.Rows[i].Cells[greenColumn].Value = greenList[i];
        if (i < redList.Count)
            dataGridView1.Rows[i].Cells[redColumn].Value = redList[i];
    }

}

Things to note:
- I used two different methods to convert the red and green columns to lists - use whichever method you feel more comfortable with. They still both use .Distinct() and .Except()

As I said right at the top of this solution though - these things are best taken care of when you are populating the datasource for the dataGridView (i.e. the datatable). I'd suggest alternatives but I don't know how you are getting your data.
   
v2
Comments
Armel_Djient 27-Mar-16 12:56pm
   
fisrt of all i am very grateful for ur reply. u can't imagine how useful are ur explanation. Between the 2 approaches given by u i prefer the first one. i found it simple.
CHill60 27-Mar-16 17:23pm
   
That one is actually my preference too :)
Sergey Alexandrovich Kryukov 27-Mar-16 13:18pm
   
5ed.
—SA
CHill60 27-Mar-16 17:23pm
   
Thank you.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900