部分代码如:private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            float i = 0;
            if (dataGridView1.CurrentCell.Value != null && dataGridView1.IsCurrentCellDirty == true)
            {
                if (!float.TryParse(e.FormattedValue.ToString(), out i))
                {
                    e.Cancel = true;
                }
            }
        }我想实现单元格只能输入数字,或者单元格为空,而我以上的代码不能实现,请问出了什么问题,或者还有其他的方法可以实现吗??
还有在代码中加入 dataGridView1.Rows[e.RowIndex].ErrorText = "输入格式不正确"; 这句代码,好像在运行时看不出什么效果,"输入格式不正确"这段字在哪显示?

解决方案 »

  1.   

    下面的代码示例处理 CellValidating 事件,以确保用户仅输入正整数。
    Private Sub dataGridView1_CellValidating(ByVal sender As Object, _
        ByVal e _
        As DataGridViewCellValidatingEventArgs) _
        Handles dataGridView1.CellValidating    Me.dataGridView1.Rows(e.RowIndex).ErrorText = ""
        Dim newInteger As Integer    ' Don't try to validate the 'new row' until finished 
        ' editing since there
        ' is not any point in validating its initial value.
        If dataGridView1.Rows(e.RowIndex).IsNewRow Then Return
        If Not Integer.TryParse(e.FormattedValue.ToString(), newInteger) _
            OrElse newInteger < 0 Then        e.Cancel = True
            Me.dataGridView1.Rows(e.RowIndex).ErrorText = "the value must be a non-negative integer"    End If
    End Sub