Trying to remove specific column from DataTable based on a property type

650 views Asked by At

I am trying to remove a column of specific type in the same way I would add one, except using .Columns.Remove()

I am using linq to grab the prop type and then a forEach() to remove the columns. I get an error:

Severity Code Description Project File Line Suppression State Error CS1503 Argument 1: cannot convert from 'System.Collections.Generic.IEnumerable' to 'System.Data.DataColumn' Fabitrack C:\data\repositories\FABITrack\Fabitrack\Models\ReportBusinessLogic.cs 141 Active

Below is my code:

//*Removing DOB from XLS file columns*/
var dob = from PropertyDescriptor props in pvPersonProps
    where props.PropertyType.Name.Contains("dob")
    select props.PropertyType;
foreach(PropertyDescriptor prop in pvPersonProps) {
    table.Columns.Remove(dob);
}

In case anyone is curious how I am adding to the table, here is some code.

var pvPersonProps = TypeDescriptor.GetProperties(typeof(PVPersonDTO)); //get prop info from PVPersonDTO object
        var pvValResProps = TypeDescriptor.GetProperties(typeof(PVValidationDTO)); //get prop info from PVValidationDTO object

        DataTable table = new DataTable();

        /*Adding colums for Person collection*/
        foreach (PropertyDescriptor prop in pvPersonProps) //iterate prop info from PVPersonDTO object and create column structure
        {
            table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);

        }
1

There are 1 answers

4
demo On

dob is a collection in your case.

So you can do something like :

foreach (var dobItem in dob)
{
     table.Columns.Remove(dobItem);
}

or

var dob = (from PropertyDescriptor props in pvPersonProps
              where props.PropertyType.Name.Contains("dob")
              select props.PropertyType).First();

foreach (PropertyDescriptor prop in pvPersonProps)
{
    table.Columns.Remove(dob);
}