Get all zero columns in a data table:

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:
  • 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.

        /// <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;

                // add to invalid column list when hasvalue is false
                if (!hasValue)

            // 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);


About msarm

Aspiring Enterprise Architect.
This entry was posted in ASP.Net 2.0. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s