c# - 使用 WriteToServer 方法插入数据 datetime 列给出异常

标签 c# sql-server datetime sqlbulkcopy

我正在尝试将 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/

相关文章:

c# - 仅 Twitter API 应用程序身份验证(使用 TweetSharp)

java - 有没有比这更简单的方法来开始当天的时间?

c# - 将列转换为行并更新

sql-server - SQL 选择具有多条记录的最大日期

c# - 将 C# DateTime 转换为 C++ std::chrono::system_clock::time_point

python - 如何合并两个数据框与重叠日期时间范围内的列

c# - 带有 OWIN TestServer 和 AutoFac 的 WebApi2 - LifetimeScope 已部署

c# - 使用 iTextSharp.dll 将 HTML 转换为 PDF

c# - 使用 LINQ 聚合列表列表

asp.net - 如何查找 SQL Server 2005 的服务器名称