views:

216

answers:

3

I'm using a foreach loop to populate each row in a DataGridView with a string. I need to search the DataGridView to make sure that I don't add a string that is already there. What is the best way to do this?

Here is my code so far:

foreach (String file in openFileDialog.FileNames)
    {                                    
        // todo: make sure file string does not already exist in DataGridView
        dataGridView1.Rows.Add();
        dataGridView1.Rows[i].Cells[1].Value = file;
        i++;
    }

Please note that there may already be file names in the DataGridView from a previous run of the code.

+2  A: 

I think this will do:

foreach(string file in dialog.FileNames)
    if (!dataGridView1.Rows.Cast<DataGridViewRow>().Any(r => r.Cells[1].Value == file))
        dataGridView1.Rows.Add(new string[]{ file });
hunter
Come on! There's so many LINQ things in here its sick, just sick. Look! You got a Cast<> and an Any()! It's gold I tell you, pure gold!
hunter
:) Your code looks awesome, but my initial approach was misguided.
LCountee
+2  A: 
foreach (String file in openFileDialog.FileNames.Distinct()) 
    {                                     
        // todo: make sure file string does not already exist in DataGridView 
        dataGridView1.Rows.Add(); 
        dataGridView1.Rows[i].Cells[1].Value = file; 
        i++; 
    } 

(Assuming C# 3.0 and LINQ extensions for IEnumerable<>)

Pierreten
While this will remove the duplicates from this `openFileDialog`, it won't check to see if the name is already in the data grid from a previous run of the code.
ChrisF
Thanks for this answer, but ChrisF is exactly right.
LCountee
Ah yes; I was assuming an empty grid.
Pierreten
I can give you the O(n^2) solution to this; but i'd heed Henk's advice instead...
Pierreten
+4  A: 

It is a good idea not to use a DataGridView as a datastore. It is a Control for displaying stuff.

It is better to bind it to some backing store and do your operations on that:

var table = new HashSet<string>();

table.Add("aa");
table.Add("bb");
table.Add("aa");

dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = table.ToList();

And when new a new batch of files comes in, add them to the HashSet and simply re-bind the Grid.

Henk Holterman