简体   繁体   English

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

[英]How to insert null value for numeric field of a datatable in c#?

Consider My dynamically generated datatable contains the following fileds Id,Name,Mob1,Mob2 考虑到我动态生成的数据表包含以下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, 我通过读取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);
    }

Any suggestion how to insert null value for numeric field during BulkCopy in c#... 任何建议如何在C#中的BulkCopy期间为数字字段插入空值...

EDIT: 编辑:

I tried this dt.Columns["Mob2"].AllowDBNull = true; 我试过了dt.Columns["Mob2"].AllowDBNull = true; but it doesn't seem to work... 但它似乎不起作用......

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. 您的DataColumn甚至知道它包含十进制值而不是字符串的剂量,也没有定义其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. 无论如何,错误表明问题是字符串-十进制转换(不是is-null问题),因此我认为您在读取第二行时收到的是空字符串“”而不是null。 Try to manully set the fields of your data array to null if they contain empty strings before you call Rows.Add 如果在调用Rows.Add之前,尝试将数据数组的字段手动设置为null(如果它们包含空字符串)。

I got it working by assigning a null value to it.... 我通过为其分配一个空值来使其工作。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM