简体   繁体   English

DataTable C#空列类型

[英]DataTable C# Empty column type

I am trying build a DataTable one row at a time using the following code. 我正在尝试使用以下代码一次建立一个DataTable。

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. 问题在于DataTable具有绑定到列的类型。 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). 有时我会在该对象索引中传递null(或空字符串),这告诉我不能将其正确转换为DateTime(在这种情况下)。 My question is what should I default this value to, or is there some way to have the DataTable ignore empty values. 我的问题是我应该将此值默认设置为什么,或者有某种方法可以使DataTable忽略空值。

Set the AllowDBNull property of the DataColumn to true, then write DataColumnAllowDBNull属性设置为true,然后编写

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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