簡體   English   中英

從datagridview和列表中刪除行

[英]Remove row from datagridview and also from list

我有這個課:

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

現在創建一個列表:

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

用自定義列填充datadridview,我使用:

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);
}

我有一個要從行中刪除的按鈕:

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

我面臨的問題是在列表中的datagridview中刪除選定的產品。
我只是不知道在這種情況下如何綁定。

您不需要foreach循環來填充網格,可以使用gridview列的DataPropertyName並讓它們為您完成工作:

productsTable.Columns.Add(new DataGridViewTextBoxColumn
{
    Name = "IDColumn",
    DataPropertyName = "ProdID",
    HeaderText = "ID of the product"
});

productsTable.Columns.Add(new DataGridViewTextBoxColumn
{
   Name = "NameColumn",
   DataPropertyName = "ProdName",
   HeaderText = "Name of the product"
});

給定上面的代碼,您可以將產品列表設置為DataGridView的DataSource,如下所示:

productsTable.DataSource = Products;

對於您的問題,考慮到您使用了上面的代碼,可以刪除選定的行,並使用以下代碼“刷新”網格:

if (productsTable.CurrentRow != null)
{
   Products.RemoveAt(productsTable.CurrentRow.Index);
   productsTable.DataSource = Products.ToList();
}

編輯:只是為了確保在索引不同的情況下刪除正確的產品,您可以刪除以下項目:

if (productsTable.CurrentRow != null)
{
   Product prod = (Product)productsTable.CurrentRow.DataBoundItem;
   Products.Remove(prod);
   productsTable.DataSource = Products.ToList();
}

DataGrid獲取productId並使用它從List<Product>查找List<Product> ,然后可以將其刪除:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM