Click here to Skip to main content
15,886,724 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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.


What I have tried:

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

    }
Posted
Updated 19-Dec-18 0:35am

1 solution

If a DataTable is null then you can't copy anything to it: there isn't anything to copy into!

It's a bit like a pocket: you have a pocket in your shirt, which you use to hold a pen. If you reach into the pocket and find there isn't a pen there, you can't sign your name on a piece of paper - and you will get very funny looks if you try!
But what you are trying to do is reach into a pocket while you aren't even wearing a shirt! You can't check the pocket for a pen, because the pocket isn't there at all.

If you want to copy data to a DataTable and the variable is null, you have to create an instance of a table to add it to.

In this case, all you need to do is use the Add method:
C#
else
    {
        dtTable.Rows.Add (from DataRow dr in dtDetails.Rows
        where dr["ID"].ToString() == Id
        select dr)
 
Share this answer
 
Comments
dipak prodhan 19-Dec-18 6:50am    
Thanks for your reply, but "dtTable.Rows.Add" is giving an error "Cannot assign to Add because it is a method group"
OriginalGriff 19-Dec-18 6:57am    
And why did you think I had brackets round it?
dipak prodhan 19-Dec-18 17:54pm    
Here i am facing an issue that is in DataTable it adding a new row but without any values.In the first column it is appending a text as [System.Data.DataRow]. Kindly help.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900