Search code examples
c#datatableado

How to store data table value in another data table with filter


How to store data table value in another data table with filter.

DataTabe dt = objProfitLossDT.Select("AppBalance <= 0");

Solution

  • Is this what you want?

    DataTable dt = objProfitLossDT.Select("AppBalance <= 0").CopyToDataTable();
    

    Note that CopyToDataTable throws an exception if there is no row in source. So you should check it:

    DataTable dt = objProfitLossDT.Clone(); // Clone is better than assigning null if you need the columns with an empty table
    DataRow[] filteredRows = objProfitLossDT.Select("AppBalance <= 0");
    if(filteredRows.Length > 0)
        dt = objProfitLossDT.Select("AppBalance <= 0").CopyToDataTable();
    

    By the way, you know that you could also use LINQ, which is much more powerful than Select:

    var filteredRows = objProfitLossDT.AsEnumerable()
        .Where(row => row.Field<int>("AppBalance) <= 0)
        .ToArray(); // if you want a DataRow[]