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?
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.
Try this code:
dt.Rows.Add(dr)
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With