Question

I need to loop through the properties of a custom object type that I'm getting back from the database and only show the columns that contain data. This means I cannot simply bind the list of objects to the datagrid. I don't want to loop through each object and see if the column is empty/null and determine in the UI to display it. What I'm thinking is in my business layer before I send the object back I would send an IEnumerable back with only those columns that should be visible. Thus I was thinking of using Linq to Object to do this, but I'm not sure that would be very pretty.

Does anyone know of a solution that I could use without a ton of IF statements that I could do to check through a large object (30 or so columns) to determine what should be shown or not.

Foreach (CustomerData customerdata in Customers) 
{ 
    if (!customerdata.address.Equals("")) 
       {
            dgvCustomerData.Column["Address"].visible = false;
         }
        //Continue checking other data columns...
}

I wish to avoid all of this in the UI and all the IFs... I'm having a brain fart on this one can anyone help me?

Thanks

Was it helpful?

Solution

Take a look at the .NET Reflection Libraries. You can use reflection to get ahold of all of an object's properties, and loop through them to find out if they are null or not. Then you could return a collection of KeyValuePair objects where Key = property name, and Value = true/false. You'd then use the keyvaluepairs to set column visibility...

OTHER TIPS

You could do the following to simplify it a bit

Action<T,string> del = (value,name) => {
  if ( value.Equals("") ) {
    dgvCustomerData.Column[name].Visible = false;
  }
};
foreach ( var data in Customers ) {
  del(data.address,"Address");
  del(data.name, "Name");
  ...
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top