简体   繁体   中英

Check for column datatypes on a on a datagridview that is not bound to a datasource in C#

I have a datagridview that is not bound to a database table. In my program, I want to check for columns that are only numeric and store them in a list.

List<string> ColumnNamesWithNumericTypes = new List<string>();

        foreach (DataGridViewColumn dgvCol in dgv.Columns)
        {
            foreach (DataGridViewRow dgvRow in dgv.Rows)
            {
                  // what is a good code to check for this condition?
              if ( the column is fully of a numeric type(int)) 
                {
                    ColumnNamesWithNumericTypes.Add(dgvCol.Name);
                }
            }
        }

Thanks.

EDIT: You could test each record against every numeric data type (aka Value Types) but the number of operations that might require would depend on what numeric data types you want, because -2.323 is a number but it's not an int. Neither is 9,223,372,036,854,775,807. So rather than testing against each Value type, here's a solution using regular expression.

ALSO: I would not be surprised if you can do this with LINQ

I only tested the RegEx portion , but you could do something like this:

using System.Text.RegularExpressions;

and then..

List<string> ColumnNamesWithNumericTypes = new List<string> ( );

        foreach (DataGridViewColumn dgvCol in dgv.Columns)
        {
            string columnname = dgvCol.Name;
            bool isnumeric = false;
            foreach (DataGridViewRow row in dgv.Rows)
            {
                if (Regex.IsMatch (row.Cells[columnname].Value , @"^[-]?([-.\d]+?)$"))
                    isnumeric = true;
                else
                {
                    isnumeric = false;
                    break;
                }
            }

            if (isnumeric == true) ColumnNamesWithNumericTypes.Add (columnname);
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM