CellPalidating时TryParse

时间:2016-06-27 18:18:10

标签: c# tryparse

在离开单元格之前,我想检查用户输入的数字或其他字符,以便我使用TryParse,这是我的代码:

    private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
    {
        int n;
        bool isNumeric = int.TryParse(dataGridView1.CurrentCell.FormattedValue.ToString(), out n);
        if (isNumeric)
        {
            //Code
        }
        else
        {
            e.Cancel = true;
        }
    }

在这两种情况下都会给我带来错误,无论我输入数字还是其他任何字符都无关紧要。

1 个答案:

答案 0 :(得分:0)

只需要使用eventArgs检查当前单元格值,因此代码如下所示:

    private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
    int n;
    bool isNumeric = int.TryParse(e.FormattedValue.ToString(), out n);
    if (isNumeric)
    {
        //Code
    }
    else
    {
        e.Cancel = true;
    }
}
相关问题