Home > front end >  Delete more than one row from the datatable
Delete more than one row from the datatable

Time:11-07

how to delete multiple row in datatable? I want to delete a number of rows from the datatable, for example, from row 10- to row 35. And save the changes to the datatable.

CodePudding user response:

You can use LINQ to select only the rows you want, and copy the result to a datatable:

Module Module1

    Function SampleDataTable() As DataTable
        Dim dt As New DataTable
        dt.Columns.Add("Col1", Type.GetType("System.String"))

        For i = 1 To 11
            Dim dr = dt.NewRow()
            dr(0) = i.ToString() & ChrW(i   64)
            dt.Rows.Add(dr)
        Next

        Return dt

    End Function

    Sub ShowDataTable(dt As DataTable)
        For Each r As DataRow In dt.Rows
            Console.WriteLine(String.Join(", ", r.ItemArray()))
        Next
    End Sub

    Sub Main()
        Dim dt = SampleDataTable()
        Console.WriteLine("Before:")
        ShowDataTable(dt)
        ' Assuming the first row is to be regarded as row number 1.
        Dim firstDelete = 5
        Dim lastDelete = 8

        dt = dt.AsEnumerable().
            Where(Function(r, i) i < firstDelete - 1 OrElse i >= lastDelete).
            CopyToDataTable()

        Console.WriteLine("After:")
        ShowDataTable(dt)

        Console.ReadLine()

    End Sub

End Module

If you give a second parameter to the Where function, it fills it with the index (0-based) of the current item.

Outputs:

Before:
1A
2B
3C
4D
5E
6F
7G
8H
9I
10J
11K
After:
1A
2B
3C
4D
9I
10J
11K
  • Related