Hypister Hypister - 16 days ago 10
C# Question

Remove row from datagridview and also from list

I have this class:

public class Product
{
public int ProdID { get; set; }
public string ProdName { get; set; }
}


Now to create a List:

public static List<Product> Products = new List<Product>();


To fill the datadridview with custom columns I use:

productsTable.Columns.Add("IDColumn", "ID of the product");
productsTable.Columns.Add("NameColumn", "Name of the product");

foreach (var product in Products)
{
productsTable.Rows.Add(product.ProdID, product.ProdName);
}


I have a button to delete from row:

private void buttonDeleteProduct_Click(object sender, EventArgs e)
{
int selectedIndex = productsTable.CurrentCell.RowIndex;
if (selectedIndex > -1)
{
productsTable.Rows.RemoveAt(selectedIndex);
}
}


The problem I'm facing is to delete the selected product in datagridview also in the List.
I just don't know how to bind in this situation.

Answer

Get productId from DataGrid and use it to lookup the product from List<Product>, then you can remove it:

int productId = (int)productsTable.Rows[selectedIndex].Cells[0].Value;
var product = products.FirstOrDefault(p => p.Id == productId);
if (product != null)
    products.Remove(product);