c# - llenar - ¿Por qué DataTable.Rows.ImportRow no funciona al pasar un nuevo DataRow creado?
how to add rows to datatable in c# (1)
Necesito agregar newRow a MyHandler y debería agregar esa fila a la tabla que se creó internamente desde el "esquema" que se pasó a MyHandler. El problema es cuando uso dt.ImportRow(row); no agrega ninguna fila. Si agrego newRow to t table y luego hago handler.Add(t.row[t.Rows.Count - 1]); entonces funciona, pero no quiero agregar a t tabla t . La t es solo para poder crear una nueva fila.
Por qué dt.ImportRow(row); no funciona? ¿Como arreglarlo?
{
var t = new DataTable();
t.Columns.Add(new DataColumn("Col1", typeof(string)));
t.Columns.Add(new DataColumn("Col2", typeof(byte)));
t.Columns.Add(new DataColumn("Col3", typeof(byte)));
t.Rows.Add("a", 1, 1);
t.Rows.Add("b", 2, 2);
// MyHandler build internal table from the scheme
var handler = new MyHandler(t.Clone());
var newRow = t.NewRow();
row["Col1"] = "c";
row["Col2"] = 3;
row["Col3"] = 3;
handler.Add(row);
}
public class MyHandler
{
DataTable dt;
public class MyHandler(DataTable scheme)
{
dt = scheme;
}
public void Add(DataRow row)
{
dt.ImportRow(row);
}
}
Solo debe usar ImportRow para agregar filas de otra DataTable. Por MSDN , las filas creadas con DataTable.NewRow deben agregar con DataTable.Rows.Add .