Search code examples
c#vb.netgenericsdatagridviewdatagridviewcolumn

Check all values of specific column to define the datatype in DGV


I'm asking your help to know if exists a fast method to check if all the values in a specific column of a DataTable/Datagridview are DateTime or numbers.

I'm trying to make a generic method to put specific formats in any column in a DGV.

I have information from TEXT files / Excel or XML files without previously data type definition

Thanks!


Solution

  • You can bury the loop in an extension method. The end result will need a loop somewhere, though, even if the loop is hidden inside Linq operations. For example, you could write this extension method:

    public static void ApplyColumnFormatting(this System.Data.DataTable table, string column, Action formatDateTime, Action formatNumeric)
    {
        bool foundNonDateTime = false;
        bool foundNonNumeric = false;
    
        DateTime dt;
        Double num;
    
        foreach (System.Data.DataRow row in table.Rows)
        {
            string val = row[column] as string;
    
            // Optionally skip this iteration if the value is not a string, depending on your needs.
            if (val == null)
                continue;
    
            // Check for non-DateTime, but only if we haven't already ruled it out
            if (!foundNonDateTime && !DateTime.TryParse(val, out dt))
                foundNonDateTime = true;
    
            // Check for non-Numeric, but only if we haven't already ruled it out
            if (!foundNonNumeric && !Double.TryParse(val, out num))
                foundNonNumeric = true;
    
            // Leave loop if we've already ruled out both types
            if (foundNonDateTime && foundNonNumeric)
                break;
        }
    
        if (!foundNonDateTime)
            formatDateTime();
        else if (!foundNonNumeric)
            formatNumeric();
    }
    

    Then you can call it like this:

    System.Data.DataTable table = ...;
    
    table.ApplyColumnFormatting("Column_Name",
        () => { /* Apply DateTime formatting here */ },
        () => { /* Apply Numeric formatting here */ }
    );
    

    This is fast in the sense that it does not check any more rows than necessary, and it does not continue checking a given type after it has been ruled out.