我正在尝试将 DateTime
插入数据类型为日期时间的列中。该值是使用 DateTime.Now
分配的,因此我知道代码中不存在错误类型的问题。
我得到的异常(exception)是:
The given value of type String from the data source cannot be converted
to type datetime of the specified target column.
这就是我指定数据表列的方式:
DataTable HODetails = new DataTable();
HODetails.Columns.Add("MasterID", typeof(long));
HODetails.Columns.Add("ItemID", typeof(int));
HODetails.Columns.Add("SubCategoryID", typeof(int));
HODetails.Columns.Add("BatchNo", typeof(string));
HODetails.Columns.Add("ExpiryDate", typeof(DateTime));
这是我设置数据的方式:
HODetails.Rows[HODetails.Rows.Count - 1]["ItemID"] = Convert.ToInt32(lblItemId.Text);
HODetails.Rows[HODetails.Rows.Count - 1]["MasterID"] =HOReceipt_ID;
HODetails.Rows[HODetails.Rows.Count - 1]["SubCategoryID"] = SubCatID;
HODetails.Rows[HODetails.Rows.Count - 1]["BatchNo"] = Convert.ToString(txtBatchNo.Text == "" ? "" : txtBatchNo.Text);
HODetails.Rows[HODetails.Rows.Count - 1]["ExpiryDate"] = DateTime.Now;
那么为什么 WriteToServer()
认为“数据源中 String 类型的值无法转换为 datetime 类型”?
最佳答案
我的问题已经解决了 我更改了 writeToServer 方法
if (DtWithTableName.Rows.Count > 0)
{
using (SqlBulkCopy s = new SqlBulkCopy(strConnection))
{
try
{
s.DestinationTableName = "HOMaterialReceiptDetails";
s.ColumnMappings.Add("MasterID", "MasterID");
s.ColumnMappings.Add("ItemID", "ItemID");
s.ColumnMappings.Add("SubCategoryID", "SubCategoryID");
s.ColumnMappings.Add("ExpiryDate", "ExpiryDate");
s.ColumnMappings.Add("BrandName", "BrandName");
s.ColumnMappings.Add("Qty", "Qty");
s.ColumnMappings.Add("FreeQty", "FreeQty");
s.ColumnMappings.Add("ReturnQty", "ReturnQty");
s.ColumnMappings.Add("ReplacementQty", "ReplacementQty");
s.WriteToServer(DtWithTableName);
}
catch (Exception)
{
IsInserted = false;
}
}
}
关于c# - 使用 WriteToServer 方法插入数据 datetime 列给出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31386927/