3

I am fetching data from datarow and facing issue when there is null value in a row column. How can I change the below mentioned code to read null values??

Datarow dr_Out[j] = dr1.Field<double?>("" + Convert.ToString(columnNames[j]) + ""); 

at this line when there is null value below error occur.

cannot set column int to be null. please use dbnull instead in datarow

after adding DBNull facing this

enter image description here

2
  • Try adding ?? (object)DbNull.Value to the end Commented Mar 11, 2020 at 15:23
  • ?? (object)DBNull.Value Commented Mar 11, 2020 at 15:35

2 Answers 2

4

You can do as suggested by the error:

    dr_Out[j] = DBNull.Value;
    double? myValue = dr1.Field<double?>("" + Convert.ToString(columnNames[j]) + "");

    if(myValue != null)
    {
        dr_Out[j] = myValue;
    }
Sign up to request clarification or add additional context in comments.

2 Comments

This will skip my step, my need is if there is null value then read that null and pass null value
And you need to write DBNull (capital B)
1

I always define my classes to accept nulls.

eg:

public DateTime? updatedTime { get; set; }

and compare for nulls in the code.

dr["updatedTime"] = (e.updatedTime is null) ? (object)DBNull.Value : (object)e.updatedTime.Value;

this way it forces a "proper" null suitable for DBs.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.