Remove empty rows at the end of a data table

Hello,

I have the following code which removes all empty rows in a data table:

dt.AsEnumerable.TakeWhile(Function (r) r.ItemArray.All(Function (c) Not String.IsNullorEmpty(c.toString.Trim))).CopyToDataTable

I would like to configure this so that instead of deleting all the empty rows, only the empty rows at the end of a data table is removed.

I attempted to replace ‘Trim’ with ‘TrimEnd’ on the code but got the error: the source contains no DataRows’.

Cheers

Hi @E.T.S

Can you try this

dt = dt.AsEnumerable.Reverse().TakeWhile(
    Function(r) r.ItemArray.All(
        Function(c) Not String.IsNullOrWhiteSpace(c.ToString.Trim)
    )
).Reverse().CopyToDataTable

Cheers!!

dt_2.AsEnumerable.where(function(x) not x(“”).equals(“”)).CopyToDataTable

Hi!

Thanks for your reply.

The suggested approach gave me this error:

image

Please could you advise which inputs to enter in the code thanks

Hey @E.T.S
try to use vb.net code:

Dim lastIndex As Integer = dt.Rows.Count - 1

For i As Integer = dt.Rows.Count - 1 To 0 Step -1
    If Not dt.Rows(i).ItemArray.All(Function(c) String.IsNullOrEmpty(c.ToString().Trim())) Then
        lastIndex = i
        Exit For
    End If
Next

For i As Integer = dt.Rows.Count - 1 To lastIndex + 1 Step -1
    dt.Rows.RemoveAt(i)
Next

@E.T.S

dt.AsEnumerable.Reverse.TakeWhile(Function (r) r.ItemArray.All(Function (c) String.IsNullOrEmpty(c.ToString.Trim))).Reverse.CopyToDataTable

Hope this works for you,Please try this query

Hi @E.T.S

Try the below syntax:

dt = dt.AsEnumerable.Reverse().SkipWhile(Function(r) r.ItemArray.All(Function(c) String.IsNullOrEmpty(c.ToString().Trim()))).Reverse().CopyToDataTable()

Hope it helps!!

Hello everyone,

Thank you for your replies

Unfortunately the solutions do not trim the end of the data table rather they trim the beginning