0
public static DataTable GetInvoicesDataTable(string checkNo, int assocBankAcctID,
    int assocAcctLedgerID, int actionItemID, bool fetchAllItems, bool isUnvoid)
{
    string sql = string.IsNullOrEmpty(checkNo) && !fetchAllItems
        ? GetSingleRecordQuery()
        : GetMultipleRecordQuery(checkNo, fetchAllItems);

    DataTable dt = DB.RtnTable(sql, DB.DB_CUSTOMER_DATA, assocBankAcctID, checkNo, actionItemID,
        assocAcctLedgerID);

    if (isUnvoid)
    {
        // return the datatable but exclude any rows where the column, "VoidDate", is not null
    }

    // else, return the datatable but exclude any rows where the column, "VoidDate", is null
}

I'm trying to figure out a succinct way to filter a DataTable based on two conditions. Is it best to modify the original DataTable somehow or should I make a copy of it, filter it, and return that? How can I accomplish that?

CarlosG90
  • 165
  • 1
  • 9
  • Does this answer your question? [How I can filter a Datatable?](https://stackoverflow.com/questions/13012585/how-i-can-filter-a-datatable) – Martheen Jul 29 '23 at 16:11

2 Answers2

0

The good way to do this is to use LINQ. LINQ is SQL like query in C# which can be used to filter and order a dataset. This will return a new DataTable from the old one after filtering.

Here is another link you can see for a detailed explanation.

LINQ query on a DataTable

Thanks.

  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 03 '23 at 00:45
0

You can use a SQL Where clause for the DataTable Select method, eg:

if (isUnvoid) {
    DataRow[] filteredRows = dt.Select("VoidDate IS NOT NULL");
    DataTable filteredDataTable = dt.Clone();
    foreach (DataRow row in filteredRows)
    {
        filteredDataTable.ImportRow(row);
    }
    return filteredDataTable;
}
return dt;
Jeremy Thompson
  • 61,933
  • 36
  • 195
  • 321