1

I have written code that is well tested for performance.

in the code I am spliting a comma seperated string and assigning it to ItemArray of a DataTable Row.

DataRow dr = dt.NewRow();
var itemArray = processedUliValue.Split(',');
dr.ItemArray = itemArray;
dt.Rows.Add(dr);

Later in the code I am converting these itemArray values to integer based on selected column names

there I am getting exception if any column is empty.

So I am looking for setting the empty values to null while assigning itemArray , I tried using DBNull.Value in comma seperated string but it did not took null, I tried null as well but that also not worked.

Is there any way to assign null using this comma seperated string to ItemArray?

2 Answers 2

6

Looks like your column, which you're trying to store DbNull.Value to, doesn't allow nulls. This works for me:

        var dt = new DataTable
        {
            Columns =
                {
                    new DataColumn("Id", typeof(int)),
                    new DataColumn("FirstName", typeof(string)) { AllowDBNull = true },
                    new DataColumn("LastName", typeof(string)) { AllowDBNull = true },
                }
        };

        var row = dt.NewRow();

        row.ItemArray = "1,,Jones".Split(',').Select(s => string.IsNullOrEmpty(s) ? (object)DBNull.Value : (object)s).ToArray();

        dt.Rows.Add(row);
Sign up to request clarification or add additional context in comments.

1 Comment

I will try it , but it seems this is the best answer
0

Why don't you check whether column value is empty before converting it to int? It seems to be simpler that way.

1 Comment

For that I've to write additional code to split the string and assign each column a value and check for null, I have many columns and I am looking for simpler way to do this

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.