Reputation: 11413
Q:
The following code:
var dtInstTotal = dtExternal.AsEnumerable()
.Union(dtEmployed.AsEnumerable())
.OrderBy(d => d.Field<string>("emp_name"));
dtInst = dtInstTotal.CopyToDataTable();//exception
throw an exception:
Value was either too large or too small for an Int16.Couldn't store <103930> in emp_num Column. Expected type is Int16. ---> System.OverflowException: Value was either too large or too small for an Int16.
Upvotes: 2
Views: 12277
Reputation: 1502546
I suspect that dtExternal
has a short
type for emp_num
, whereas dtEmployed
has some other type (int
, long
or maybe just ushort
) - or maybe vice versa. CopyToDataTable
just uses the types from the first table containing the first row it sees, and then it's having problems when it comes across a value for a column with the same name from a different table. From the docs:
The schema of the destination table is based on the schema of the first DataRow row in the source sequence. The table metadata is extracted from the DataRow metadata and the table values from the column values of the DataRow.
Basically: make sure your two original tables have the same schema.
EDIT: We don't know what your methods to populate the two original DataTable
s look like - but you may find that by creating the DataTable
first, explicitly setting the type of emp_num
, and then filling the table, that will be okay.
You could even leave your original methods alone, and build a new DataTable
with the right schema, then call
dtInstTotal.CopyToDataTable(tableWithCorrectSchema, LoadOption.PreserveChanges);
Upvotes: 1
Reputation: 4127
i think the datatable structure in dtInst or dtInstTotal for emp_num is int16
change it to int32
Upvotes: 1