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.