locked
Append the output of query into DataTable RRS feed

  • Question

  • User-2073689554 posted

    Hi, I have a requirement to check if DataTable is null then copy the row to DataTable otherwise need to append the row to the DataTable. 

    if (dtTable == null)
        {
            dtTable = (from DataRow dr in dtDetails.Rows
                       where dr["ID"].ToString() == Id
                       select dr).CopyToDataTable();
        }
        else
        {
           // Here Need to Add a new row in DataTable and append the output of 
             query into DataTable ie dtTable.
    
           DataRow row = selectedTable.NewRow();
    
            dtTable  = (from DataRow dr in dtDetails.Rows
            where dr["ID"].ToString() == Id
            select dr)
            // Need help here
    
        }
    Thanks.

    Wednesday, December 19, 2018 11:30 AM

All replies

  • User1724605321 posted

    Hi dipakprodhan.kol ,

    You can refer to below code sample :

    if (dtTable == null)
    {
        dtTable = (from DataRow dr in dtDetails.Rows
                    where dr["ID"].ToString() == Id
                    select dr).CopyToDataTable();
    }
    else
    {
        var result = from DataRow dr in dtDetails.Rows
                        where dr["ID"].ToString() == Id
                        select dr;
    
        foreach (var item in result)
        {   
                
            dtTable.Rows.Add(item.ItemArray);
        }
    }

    Best Regards,

    Nan Yu

    Thursday, December 20, 2018 7:25 AM
  • User842257015 posted

    Hi,

    if (dtTable == null)
    {
       dtTable = dtDetails.Copy();
    }
    else
    {
        var filterResponse = dtDetails.AsEnumerable().Where(x => x.Field<string>("ID") == Id);
    if(filterResponse.Count()>0)
    dtTable.Merge(filterResponse.CopyToDataTable()); } dtTable.AcceptChanges();

    Note: if you wanna unique rows in dtTable, then compare and remove duplicate before start merge.

    Thanks, 

    Friday, December 28, 2018 7:26 AM