Copy source datatable to destination datatable with the schema of destination - c#

I'm trying to copy the data from source dt to destination datatable.
source datatble types are sting and destination datatble types contains datetime along with strings.
datatable dt2=new datatable();
foreach (DataRow row in dt1.Rows)
{
dt2.ImportRow(row); //String was not recognized as a valid DateTime.
}
I get String was not recognized as a valid DateTime as destination column type is datetime and is not able to import that row.

Use DataTable.Clone() to setup a new DataTable object with the existing schema. Then add any additional columns you might need.
DataTable dt1 = MyData();
DataTable dt2 = dt1.Clone();
foreach(DataRow row in dt1.Rows)
{
dt2.ImportRow(row);
}

Related

Validation of Excel file data before importing to Database

I'm trying to read data from an Excel file to a DataTable. I know that we can assign different DataTypes for a DataColumn when adding columns to a DataTable. So far I have tried the following,
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[2]
{
new Datacolumn("column1", typeof(string)),
new DataColumn("column2", typeof(int))
});
And my excel file has data in two columns as follows,
column1------column2
abc----------------230
def----------------230tr
As you can see above, the second row second column has a value of '230tr' which the DataTable should not accept an throw an exception with the invalid data field and row number.
Praveena.
you can try in that way.
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[2]
{
new DataColumn("column1", typeof(int)),
new DataColumn("column2", typeof(string))
});
dt.Clear();
try
{
string input = string.Empty;
input = Console.ReadLine();
if (Regex.IsMatch(input, #"^[a-zA-Z]+$"))
{
dt.Rows.Add(1, input);
}
Console.WriteLine(dt.Rows[0]["column2"]);
Console.ReadKey();
}
catch(Exception ex)
{
Console.WriteLine(ex);
Console.ReadKey();
}
In your code, where you are reading the excel values to insert, you should employ the C# function: [Int32.TryParse][1] or float.Try​Parse;
which will tell you whether the string will convert to a float (or integer) in which case don't insert it.
You can see a detailed example/answer here:
Thank you everyone for their response and I found an easy solution for my question while working with DataTables. My main task was to read data rows from an Excel file sheet and validate each row data before adding it to my database table(using OracleBulkCopy) and notify the user with any invalid data fields in the Excel file sheet.
While I was importing data into the DataTable from the Excel file sheet using oda.Fill(dt); I realized that some of the DataRow fields are empty(null) during the process of data addition to DataTable.
As I have mentioned above in the main question we can assign the DataType for a DataColumn in a DataTable as follows,
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[3]
{
new Datacolumn("column1", typeof(string)),
new DataColumn("column2", typeof(double)),
new DataColumn("column3", typeof(DateTime))
});
And my Excel file sheet would be as follows,
column1-----------------column2----------------------column3
abcd----------------------20000-------------------------20-Dec-2018
efgh-----------------------56500.5----------------------xyz17-Mar-2018
ijklm-----------------------67000------------------------1-Jan-2018
In the above table 3rd row 3rd column RowData is in invalid date type (xyz17-Mar-2018). While performing oda.Fill(dt); for the above table, this data field gets added as a null RowData to the DataTable. It would be the same for other columns if the importing data fields are not in the type of defined DataColumn type. So My final step was to check each row data of DataTable which has a null field and throw the user with an error message mentioning the row number and column name.
int errorRowNumber = 0;
private bool validateDataTableData(DataTable dt, string dtColumnName)
{
Boolean isTrue = false;
foreach (DataRow r in dt.Rows)
{
if(!string.IsNullOrEmpty(r[dtColumnName].ToString()))
{
isTrue = false;
errorRowNumber = dt.Rows.IndexOf(r) + 2;
break;
}
}
return isTrue;
}

How to assign one datarow values to another datarow

I want to copy first row of one DataTable to first row of another DataTable. I did as shown below but it throws error like
Property or indexer 'System.Data.DataRowCollection.this[int]' cannot be assigned to -- it is read only
DataTable dt = GetTable();
DataTable dt1 = GetTable1();
dt.Rows[0] = dt1.Rows[0];
You have to copy it field by field.
The data row within the datatable is immutable, which means that you can change the values of its fields, but not the object itself, being said that you should copy the values from you source row to the destination row.
Assuming your datatables have the same columns:
DataTable dt = GetTable();
DataTable dt1 = GetTable1();
foreach(DataColumn column in dt.Columns)
{
dt.Rows[0][column] = dt1.Rows[0][column];
}
Hope this helps.

Selecting specific columns from a dataTable and copy it to another DataTable

I have a DataTable Dt1 and another DataTable Dt2.
Dt1 contains many columns and rows and Dt2 is basically empty
I know I should use Dt1.Select to select the specific DataTaRow [] but how can I copy them to Dt2
DataRow [] row = Dt1.Select("ID,MIN_VALUE,MAX_VALUE");
how can i copy them to Dt2?
For .Net Framework 3.5+
You can use CopyToDataTable method.
Returns a DataTable that contains copies of the DataRow objects, given
an input IEnumerable object.
DataTable dt1 = new DataTable();
DataRow[] dr = dt.Select("Your string");
DataTable dt2 = dr.CopyToDataTable();

How to change type datatable column [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How To Convert The DataTable Column type?
How can we change the datatable column type if table already have value?
Changing data type of datatable after get filled is not possible but one of the work abound for this is clone datatable and change type
First way
//clone datatable
DataTable dtCloned = dt.Clone();
//change data type of column
dtCloned.Columns[0].DataType = typeof(Int32);
//import row to cloned datatable
foreach (DataRow row in dt.Rows)
{
dtCloned.ImportRow(row);
}
second way
and other way to do it is like this , fill schema first - than change column datatype and than fill datable
adapter.FillSchema(table, SchemaType.Source);
table.Columns[0].DataType = typeof (Int32);
adapter.Fill(table);
third way
one more way to do it is
System.Data.DataTable dt = new System.Data.DataTable();
dt.Columns.Add("Col1", typeof(int));
dt.Rows.Add(1);
System.Data.DataTable dt2 = new System.Data.DataTable();
dt2.Columns.Add("Col1", typeof(string));
dt2.Load(dt.CreateDataReader(), System.Data.LoadOption.OverwriteChanges);

Getting Exception : Here The given DataRow is not in the current DataRowCollection

I have facing Problem..
DataTable Dt1 = table1;
DataTable Dt2 = Dt1.Copy();
DataRow[] row = Dt1.Select("Name = 'Test'");
foreach (DataRow row in Dt2)
{
Dt2.Rows.Remove(row); // Here The given DataRow is not in the current DataRowCollection
}
Its giving the exception because I Filter the date from Different Row and Removing It from Different Row.
Thanks, Shivam
Your current code removes all rows from the Dt2 DataTable because you overwrite the selected row from Dt1 when you loop through your foreach statement.

Categories

Resources