DataTable.ImportRow does not add rows

I am trying to make a DataTable and then add a couple of lines to it. Here is my code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;


namespace thisNamespace
{
    class Program
    {
        static void Main(string[] args)
        {
            DataTable dt=new DataTable();
            dt.Columns.Add("XYZID");
            DataRow dr=dt.NewRow();
            dr["XYZID"]=123;
            dt.ImportRow(dr);
            dr["XYZID"] = 604303;
            dt.ImportRow(dr);

        }
    }
}

When I exit the program, it is drsuccessfully initialized and filled with values, but after that the ImportRow(dr)number of lines dtis still 0. I feel that I must be missing something obvious. What's going on here?

+5
source share
4 answers

Try this code:

dt.Rows.Add(dr)

+6
source

If a row is detached (the same as it was first created), then ImportRows fails (without exception) - to be able to import rows that you must add to the table. After that, you can import it into other tables.

+3
source

DataTable table = new DataTable();
table.Columns.Add("Dosage", typeof(int));
    table.Columns.Add("Drug", typeof(string));
    table.Columns.Add("Patient", typeof(string));
    table.Columns.Add("Date", typeof(DateTime));

    //
    // Here we add five DataRows.
    //
    table.Rows.Add(25, "Indocin", "David", DateTime.Now);
    table.Rows.Add(50, "Enebrel", "Sam", DateTime.Now);
    table.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now);
    table.Rows.Add(21, "Combivent", "Janet", DateTime.Now);
    table.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now);
+1

:

 dt.Rows.Add(dr);

, :

 dt.AcceptChanges();
0

All Articles