以确保用户仅输入正整数。private void dataGridView1_CellValidating(object sender,
    DataGridViewCellValidatingEventArgs e)
{
    dataGridView1.Rows[e.RowIndex].ErrorText = "";
    int newInteger;    // 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) { return; }
    if (!int.TryParse(e.FormattedValue.ToString(),
        out newInteger) || newInteger < 0)
    {
        e.Cancel = true;
        dataGridView1.Rows[e.RowIndex].ErrorText = "the value must be a non-negative integer";
    }
}

解决方案 »

  1.   

    未测试Private Sub dataGridView1_CellValidating(ByVal sender As Object, ByVal e As DataGridViewCellValidatingEventArgs) 
        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 
        End If 
        If Not Integer.TryParse(e.FormattedValue.ToString(), newInteger) OrElse newInteger < 0 Then 
            e.Cancel = True 
            dataGridView1.Rows(e.RowIndex).ErrorText = "the value must be a non-negative integer" 
        End If 
    End Sub