Checking for numeric values in columns of datagridview

时间:2016-04-12 00:35:17

标签: c# datagridview

I have a utilities script that looks like this

public static bool CheckForNumbersInNumbersColumns(DataGridView datagridviewname)
    {
        bool numbersarenotpresent = false;
        for (int i = 0; i < datagridviewname.Rows.Count; i++)
        {
            if (typeof (float) == datagridviewname.Rows[i].Cells[7].Value.GetType() || typeof (float) == datagridviewname.Rows[i].Cells[8].Value.GetType())
            {
                numbersarenotpresent = true;
                break;
            }
            else
            {
                numbersarenotpresent = false;
            }
        }
        return numbersarenotpresent;
    }

It keeps returning false if I test it with any string value of just single letters in the cell, I would like it to return true and just stop running when that happens. Any help would be greatly appreciated!

1 个答案:

答案 0 :(得分:1)

You can grab the value of each cell you want to check, and do a TryParse. If TryParse fails, it's an indication that the value was not a float.

More info on TryParse here.

public static bool CheckForNumbersInNumbersColumns(DataGridView datagridviewname)
{
    for (int i = 0; i < datagridviewname.Rows.Count; i++)
    {
        var value = datagridviewname.Rows[i].Cells[7].Value.ToString();
        var value2 = datagridviewname.Rows[i].Cells[8].Value.ToString();
        float floatValue;
        float floatValue2;

        if (!Single.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out floatValue) || 
            !Single.TryParse(value2, NumberStyles.Any, CultureInfo.InvariantCulture, out floatValue2))
        {
            return true;
        }
    }
    return false;
}