如何在 C# 中的数据表的数字字段中插入空值?

发布于 2024-09-03 03:34:39 字数 873 浏览 1 评论 0原文

考虑我的动态生成的数据表包含以下字段 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

淡莣 2024-09-10 03:34:39

您确定该错误不会发生在您的应用程序中的其他地方吗?
您的 DataColumn 如何知道它包含十进制值而不是字符串,您没有定义它的 DataType。

无论如何,错误表明问题是字符串 - 十进制转换(不是 is-null 问题),所以我认为当您阅读第二行时,您会收到一个空字符串“”而不是 null。
如果在调用 Rows.Add 之前数据数组的字段包含空字符串,请尝试将其手动设置为 null

Are 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

银河中√捞星星 2024-09-10 03:34:39

我通过给它分配一个空值来让它工作......

if(dr["Mob2"] == "")
  dr["Mob2"] =null;

I got it working by assigning a null value to it....

if(dr["Mob2"] == "")
  dr["Mob2"] =null;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文