Reputation: 1399
I want to copy some rows of data table, to another one. I tried this code :
DataTable Result = new DataTable();
for(int i = 5; i < PageSize && i < TransactionDataTable.Rows.Count ; i++)
{
DataRow dr = (DataRow)TransactionDataTable.Rows[i];
Result.ImportRow(dr);
}
string MobileNumber = TransactionDataTable.Rows[0]["MobileRegistration_MobileNumber"].ToString();
string MobileNumber2 = Result.Rows[0]["MobileRegistration_MobileNumber"].ToString();
TransactionDataTable is a dataTable with more than 1000 rows.
in above code, MobileNumber has proper vallue, but MobileNumber2 dosent have. I got this error in last line ( in assigning MobileNumber2 value) :
Additional information: Column 'MobileRegistration_MobileNumber' does not belong to table .
It seems that the rows didnt copy properly, in Result dataTable.
whats the wrong with this code?
and I tried Result.Rows.Add(dr);
instead of Result.ImportRow(dr);
but an exception throw with this information:
This row already belongs to another table.
Thanks for any helping...
Upvotes: 1
Views: 1978
Reputation: 16310
You are making new datatable Result
without any column. So, make sure you are bringing all columns from the table which you are going to copy.
In your case, you can clone the TransactionDataTable
and then import the row.
The updated copy implementation will be like this :
DataTable Result = TransactionDataTable.Clone();
for(int i = 5; i < PageSize && i < TransactionDataTable.Rows.Count ; i++)
{
DataRow dr = (DataRow)TransactionDataTable.Rows[i];
Result.ImportRow(dr);
}
string MobileNumber = TransactionDataTable.Rows[0]["MobileRegistration_MobileNumber"].ToString();
string MobileNumber2 = Result.Rows[0]["MobileRegistration_MobileNumber"].ToString();
Upvotes: 1