简体   繁体   中英

How to insert Null value to DataTable using ItemArray

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?

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);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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