Ananth Ramasamy Meenachi - www.msarm.com
I got an interesting requirement and all that I need to do show is only all non-zero columns in a report.For the below data:
Expected result:Solution:
Need to find all zero columns list.
For default datagrid: Just delete columns from datatable with all zero column list and bind it.
For dynamic datagrid create BoundColumn or ButtonColumn for all valid columns, ignoring the all zero columns and then bind it.
Code:
/// <summary> /// Get all zero columns in a given data table /// </summary> /// <param name="table"></param> /// <returns></returns> public static List<string> GetAllZeroColumns(DataTable table) { // initialize invalid column list List<string> invalidColumns = new List<string>(); // return empty list when table count is zero if (table.Rows.Count == 0) return invalidColumns; // loop each column from first to last // column and in each column loop each row item // in that column from top to bottom, anyhwere // if we find a value greater than zero then // break that column and look for next column. // finally all zero column will be added to the // invalid list. foreach (DataColumn col in table.Columns) { // initialise has value flag for each column bool hasValue = false; // loop each row in a column foreach (DataRow data in table.Rows) { // row item value with non-zero value // breaks the current column and looks // for next column to increase the performance. if (!IsZeroOrNull(data[col.Ordinal])) { hasValue = true; break; } } // add to invalid column list when hasvalue is false if (!hasValue) invalidColumns.Add(col.ColumnName); } // finally returns invalid columns return invalidColumns; } /// <summary> /// Check the given number is zero or null /// </summary> /// <param name="rowItem"></param> /// <returns></returns> public static bool IsZeroOrNull(object rowItem) { decimal zeroDecimal = new decimal(0); return rowItem == null ? true : rowItem.Equals(zeroDecimal); }