Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataTable.ImportRow is not adding rows

Tags:

c#

datatable

I'm trying to make a DataTable and then add a couple rows to it. Here's 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 step through the program, dr is successfully initialized and populated with values, but then after ImportRow(dr), the count of rows in dt is still 0. I feel like I must be missing something obvious. What's going wrong here?

like image 725
sigil Avatar asked Apr 05 '13 02:04

sigil


3 Answers

If the row is detached (as it is when it is first created) ImportRows fails silently (no exception) - to be able to import rows you have to Add it into the table. Afterwards you can import it into other tables.

like image 58
Sinisa Hajnal Avatar answered Nov 20 '22 12:11

Sinisa Hajnal


Try this code:

dt.Rows.Add(dr)

like image 7
Kelmen Avatar answered Nov 20 '22 10:11

Kelmen


Its May Help you

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);
like image 1
Sagar Hirapara Avatar answered Nov 20 '22 10:11

Sagar Hirapara