In C#, how can I enter a null value for a datatable's numeric field?

c# insert null numeric sqlbulkcopy

Question

Consider The fields in my dynamically produced datatable are as follows:Id,Name,Mob1,Mob2

If my datatable has this, the entry is successful.

Id Name Mob1        Mob2
1  acp  9994564564  9568848526

But in this situation, it fails, stating,

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 read a csv file to create my datatable.

    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 ideas on how to bulk copy a numeric field in c# with a null value?

EDIT:

I did it.dt.Columns["Mob2"].AllowDBNull = true; nevertheless, it doesn't seem to function...

1
0
5/28/2010 6:50:34 AM

Accepted Answer

By giving it a null value, I was able to get it to function.

if(dr["Mob2"] == "")
  dr["Mob2"] =null;
1
5/28/2010 9:25:29 AM

Popular Answer

Are you certain that the mistake doesn't appear in another part of your application? Since you did not specify the DataType of your DataColumn, how does it even know that it contains decimal numbers and not strings?

However, the error indicates that the issue is a string to decimal conversion (not an is-null issue), thus I believe that when you read the second line, you obtain an empty string "" rather than a null. If your data array's fields include empty strings before you call, try manually setting them to null.Rows.Add



Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow