简体   繁体   中英

DataTable C# Empty column type

I am trying build a DataTable one row at a time using the following code.

foreach (var e in Project.ProjectElements[hi.FakeName].Root.Elements()) {
        index = 0;
            object[] obj=new object[count];
            foreach (var holdingColumn in names) {
                string d = e.Attribute(holdingColumn.Key).Value;
                obj[index++] = d;
            }
            dt.Rows.Add(obj);
        }

The problem is the DataTable has types tied to the columns. Sometimes im passing null (or an empty string) in that object index and it is telling me that it cant be converted properly to a DateTime (in this case). My question is what should I default this value to, or is there some way to have the DataTable ignore empty values.

Set the AllowDBNull property of the DataColumn to true, then write

if (String.IsNullOrEmpty(d))
    obj[index++] = DBNull.Value;
else
    obj[index++] = d;

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