Data Table + delete a row in c# using loop

前端 未结 3 1661
故里飘歌
故里飘歌 2021-01-04 08:26

I have a data table and I want to delete a row here is my code it\'s throwing me an exception

foreach (DataRow row in dt1.Rows)
{
    if ((row[\"Name\"] == \         


        
相关标签:
3条回答
  • 2021-01-04 08:31

    Instead of using dt1.Rows, use dt1.Select()

    The goal here is not to use the collection itself, but rather an array of row that is not the Rows collection

    0 讨论(0)
  • 2021-01-04 08:39

    This is how I did it when I ran into this issue.

                Dim index As Integer = 0
                Dim count As Integer = resultsDT.Rows.Count - 1
                For i As Integer = 0 To count
                    If resultsDT.Rows(index).Item("something") = "something" Then
                        resultsDT.Rows(index).Delete()
                        resultsDT.AcceptChanges()
                        index = index - 1
                    End If
    
                    index = index + 1
                    i = i + 1
                Next
    
    0 讨论(0)
  • 2021-01-04 08:41

    Create a list of rows to delete while iterating over DataTable.Rows, then delete them all separately.

    Non-LINQ solution:

    List<DataRow> rowsToDelete = new List<DataRow>();
    foreach (DataRow row in dt1.Rows)
    {
        if ((row["Name"] == "Select a Lookbook") || 
            (row["Name"] == "Create a new Lookbook"))
        {
            rowsToDelete.Add(row);
        }
    }
    foreach (DataRow row in rowsToDelete)
    {
        row.Delete();
    }
    dt1.AcceptChanges();
    

    LINQ solution:

    List<DataRow> rowsToDelete = dt1.Rows.AsEnumerable()
        .Where(row => (row["Name"] == "Select a Lookbook") || 
                      (row["Name"] == "Create a new Lookbook"))
        .Tolist();
    foreach (DataRow row in rowsToDelete)
    {
        row.Delete();
    }
    dt1.AcceptChanges();
    
    0 讨论(0)
提交回复
热议问题