如何在 C# 中的数据表的数字字段中插入空值?
考虑我的动态生成的数据表包含以下字段 Id,Name,Mob1,Mob2
如果我的数据表有这个,它会成功插入,
Id Name Mob1 Mob2
1 acp 9994564564 9568848526
但是当它像这样时,它会失败,说,
Id Name Mob1 Mob2
1 acp 9994564564
给定值数据源中的 String 类型无法转换为指定目标列的十进制类型。
我通过读取 csv 文件生成数据表,
CSVReader reader = new CSVReader(CSVFile.PostedFile.InputStream);
string[] headers = reader.GetCSVLine();
DataTable dt = new DataTable();
foreach (string strHeader in headers)
{
dt.Columns.Add(strHeader);
}
string[] data;
while ((data = reader.GetCSVLine()) != null)
{
dt.Rows.Add(data);
}
任何建议如何在 c# 中的 BulkCopy 期间为数字字段插入空值...
编辑:
我尝试了dt.Columns["Mob2"].AllowDBNull = true;
但它似乎不起作用......
Consider My dynamically generated datatable contains the following fileds Id,Name,Mob1,Mob2
If my datatable has this it get inserted successfully,
Id Name Mob1 Mob2
1 acp 9994564564 9568848526
But when it is like this it gets failed saying,
Id Name Mob1 Mob2
1 acp 9994564564
The given value of type String from the data source cannot be converted to type decimal of the specified target column.
I generating my datatable by readingt a csv file,
CSVReader reader = new CSVReader(CSVFile.PostedFile.InputStream);
string[] headers = reader.GetCSVLine();
DataTable dt = new DataTable();
foreach (string strHeader in headers)
{
dt.Columns.Add(strHeader);
}
string[] data;
while ((data = reader.GetCSVLine()) != null)
{
dt.Rows.Add(data);
}
Any suggestion how to insert null value for numeric field during BulkCopy in c#...
EDIT:
I tried this dt.Columns["Mob2"].AllowDBNull = true;
but it doesn't seem to work...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您确定该错误不会发生在您的应用程序中的其他地方吗?
您的 DataColumn 如何知道它包含十进制值而不是字符串,您没有定义它的 DataType。
无论如何,错误表明问题是字符串 - 十进制转换(不是 is-null 问题),所以我认为当您阅读第二行时,您会收到一个空字符串“”而不是 null。
如果在调用
Rows.Add
之前数据数组的字段包含空字符串,请尝试将其手动设置为 nullAre you sure the error doesn't occur somewhere else in your application?
How dose your DataColumn even know that it contains decimal values and not strings, you do not define its DataType.
Anyway the error says that the problem is a string - decimal conversion (not an is-null issue), so I think you receive an emty string "" rather than null when you read the second line.
Try to manully set the fields of your data array to null if they contain empty strings before you call
Rows.Add
我通过给它分配一个空值来让它工作......
I got it working by assigning a null value to it....