Datatable ImportRow

2019-07-15 02:16发布

问题:

DataSet dsUdpated = new DataSet()
DataTable dtUpdated = dsUpdated.Tables.Add();
dtUpdated = dsOriginal.Tables[0].Clone();   // Guarenteed ds.Tables[0] has rows
dsUpdate.Tables[0].ImportRow(row); // row is one of the filtered row in 

But the ImportRow doesnt seem to add the rows!. dsUpdate.Tables[0] doesnt contain the row. But a row is added. Please help!

回答1:

Here's what you're doing wrong.

DataTable dtUpdated = dsUpdated.Tables.Add();
dtUpdated = dsOriginal.Tables[0].Clone();

In the first line, you are declaring your object and initializing it to the result of an Add operation on the DataSet's Tables collection. In the second line, you are setting to to something else entirely!

dtUpdated may very well refer to the same object in memory as dsUpdated.Tables[0] after the first line of code, but the variable itself is not a constant reference to that object. Indeed, in the second line, you have set it to a different object, the result of another table's Clone() method. If the variable ever pointed to the same object as dsUpdated.Tables[0], it does not anymore. It's similar to stating

int x = 5;
x = 6;

In the first line, the value of x is 5. In the second, you've replaced that value with 6. Similarly, with your table variable, the value is a reference. You've replaced one reference with another. Make sense?

Clone the table first, then add that table to the dataset. Now dsUpdated.Tables[0] will contain the cloned structure of dsOriginal.Tables[0] and your import should work as expected.



回答2:

Please try this:

DataTable dt=dsOriginal.Tables[0].Clone(); 
dsUpdated.Tables.Add(dt);
DataTable dtUpdated=dt;


回答3:

Please clone the DataTable first.

DataTable dt=table.Clone();

foreach (DataRow row in table.Select("AirAvail_Id=0"))
{                     
    dtAirAvail.ImportRow(row);
}

This will work fine.



标签: c# .net dataset