Lord-David
Lord-David

Reputation: 545

Removing column based on the content of the cells

I need to delete the whole column in a DataGridView based on a certain condition. My DataGridView columns consists of numbers (1,2 and 3) the condition would be to delete all columns that does not contain (1,2 and 3). For Example if the column has only (1 and 3) it should be deleted.

How do I Overcome this? as many threads I went through only cover when you are certain of an index like below.

myGridView.columns.RemoveAt(index);

Some suggest hiding columns and thats not what I want, I want to completely remove the column from the DataGridView.

Upvotes: 1

Views: 409

Answers (1)

Reza Aghaei
Reza Aghaei

Reputation: 125207

While it's better to do the job using data source of the DataGridView, but if the control is not bound to a data source, you can also use linq to get values from columns and check for some criteria, for example:

dgv1.Columns.Cast<DataGridViewColumn>()
    .ToList().ForEach(c =>
    {
        var values = dgv1.Rows.Cast<DataGridViewRow>().Where(r => !r.IsNewRow)
            .Select(r=>r.Cells[c.Index].Value).ToList();
        if (!values.Contains(1)) //your custom criteria
            dgv1.Columns.Remove(c);
    });

Here is a really simple test. Load dgv1 this way:

dgv1.ColumnCount = 2;
dgv1.Rows.Add(1, 2); 
dgv1.Rows.Add(3, 4); 

Then use above code to delete columns and it just removes the last column.

Upvotes: 1

Related Questions