Find a row in a DataGridView

I use a foreach loop to populate each row in a DataGridView with a row. I need to find a DataGridView to make sure that I am not adding a row that already exists. What is the best way to do this?

Here is my code:

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 be file names in the DataGridView from the previous code run.

+3
source share
3 answers

Using a DataGridView as a data store is not recommended. This is a control for displaying material.

It’s better to bind it to some storage and do the following:

var table = new HashSet<string>();

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

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

And when a new batch of files appears, add them to the HashSet and simply unbind the Grid.

+4

, :

foreach(string file in dialog.FileNames)
    if (!dataGridView1.Rows.Cast<DataGridViewRow>().Any(r => r.Cells[1].Value == file))
        dataGridView1.Rows.Add(new string[]{ file });
+2
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++; 
    } 

( # 3.0 LINQ IEnumerable < > )

+2

Source: https://habr.com/ru/post/1744555/


All Articles