Home > Net >  How can I accept null in the DataTable for bool columns?
How can I accept null in the DataTable for bool columns?

Time:08-18

Here I tried to accept null but while creating the header eachprop.propertyType is not accepting null.
I want to add NULL values to rows for boolean columns for which I am getting false, kindly help me

dt = new DataTable
                {
                    TableName = "ABC"
                };
    
                propInfos = new List<PropertyInfo>();
                propInfos = typeof(ValueInfo).GetProperties()
                    .ToList();
    
                propInfos.ForEach(eachProp =>
                {
                    dt.Columns.Add(eachProp.Name, eachProp.PropertyType);
                });
                CreateTableToSqlFromDataTable(connString, dt);
    
                rowCount = 0;
                if (lInput.ValueList.Any())
                {
                    lInput.ValueList.ForEach(eachColumnInfo =>
                    {
                        DataRow dr = dt.NewRow();
                        propInfos.ForEach(eachProp =>
                        {
                            dr[eachProp.Name] = eachProp.GetValue(eachColumnInfo) ;
                        });
                        dt.Rows.Add(dr);
    
                        if ((rowCount != 0 && rowCount % 10000 == 0) || rowCount == lInput.ValueList.Count() - 1)
                        {
                            WriteToSql(connString, dt);
                            dt.Clear();
                            System.Diagnostics.Debug.WriteLine(DateTime.Now.ToShortTimeString()   " | "   "Row copied "   rowCount.ToString());
                        }
                        rowCount  ;
                    });
                }

this is my class structure:

[ProtoMember(1)]
private string id;
    public string ID
    {
        get { return id; }
        set { id = value; }
    }

    [ProtoMember(2)]
    private bool  b;
    public bool _b
    {
        get { return b; }
        set { b = value; }
    }

    [ProtoMember(3)]
    private bool? c;
    public bool? _c
    {
        get { return c; }
        set { c = value; }
    }

    [ProtoMember(4)]
    private bool? d;
    public bool? _d
    {
        get { return d; }
        set { d = value; }
    }

I'm trying to build the DataTable from the class properties and value is adding is coming from ui for those class properties. For properties c and d I am sending null from ui and for property b m sending false

CodePudding user response:

You need to use DBNull.Value instead of null. You can use a null-coalescing expression for this

dr[eachProp.Name] = eachProp.GetValue(eachColumnInfo) ?? (object)DBNull.Value;

The cast to object is needed to avoid type-inference problems.

CodePudding user response:

Try this:

var val = eachProp.GetValue(eachColumnInfo);

dr[eachProp.Name] = (val as bool?) == false) ? null : val;
  •  Tags:  
  • c#
  • Related