0

I'm passing IEnumerable as a parameter and I'm trying to add rows into a DataGridView (DGV) using a foreach loop. Just before I add the rows in the DGV, I clear the existing data in the DGV using datagridview1.Rows.Clear();

But my parameter value gets cleared after the DGV is cleared.

public void LoadDGV(IEnumerable<DataGridViewRow> products)
 {
      if (products == null) return;
      datagridview1.DataSource = null; //products contains values until this line
      datagridview1.Rows.Clear(); //products gets cleared here
      foreach (DataGridViewRow prod in products)
            { 
                datagridview1.Rows.Add(
                    (int)prod.Cells["ProductID"].Value,
                    prod.Cells["ProductName"].Value.ToString();
                    prod.Cells["CategoryName"].Value.ToString(),
                    prod.Cells["QuantityPerUnit"].Value,
                    prod.Cells["UnitPrice"].Value,
                   );
            }
}

Why is this happening after datagridview1.Rows.Clear();?

EDIT:

I have a text box to search for product names and an event handler is triggered for a text change. I'm searching within a DGV to filter the Products which contains the string entered by the user.

public IEnumerable<DataGridViewRow> SearchByProductName(string ProductName)
        {
            IEnumerable<DataGridViewRow> rows = datagridview1.Rows
            .Cast<DataGridViewRow>()
            .Where(r => r.Cells["ProductName"].Value.ToString().Contains(ProductName))
            .Select(r => r).ToList();

             return rows;
        }

Products is nothing but rows that i get from the above function.

Roxana Sh
  • 294
  • 1
  • 3
  • 14
  • From where do you get `products`? – Chetan Sep 08 '19 at 03:18
  • Please check my edited post. – Keerthana B Sep 08 '19 at 04:24
  • `products` is a reference to the `datagridview1` rows. You are clearing `datagridview1` because of which `products` are getting cleared which makes sense. Did you intend to clear `dgvProducts` ? – Boney Sep 08 '19 at 04:31
  • I thought i was passing a value (copy) to the function. Is it not? And, yes I intend to clear datageridview1. – Keerthana B Sep 08 '19 at 04:40
  • That's how you should not implement filter. You should filter the original data source from which you load the data in grid and rebind it to the grid. – Chetan Sep 08 '19 at 04:52
  • I believe this answers your question: https://stackoverflow.com/questions/2774099/tolist-does-it-create-a-new-list . Since the elements of the enumerable are complex objects, as soon as they are removed/deleted, your enumerable no longer has anything to reference and thus it is empty. – o_weisman Sep 08 '19 at 09:23

0 Answers0