DataGridView中如何控制其中一列只能输入数字?

解决方案 »

  1.   

    你可以在如下事件里对输入进行验证并可取消输入:DataGridView.CellValidating 事件
    在单元格失去输入焦点时发生,并启用内容验证功能。 比如下面的代码:
    下面的代码示例处理 CellValidating 事件,以确保用户仅输入正整数。此示例摘自 VirtualMode 参考主题中提供的一个更大示例。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";
        }
    }
      

  2.   

    你最好通过上面的方法 来做,因为DataGridView没有一个默认的列是专门用来输入数字的.
      

  3.   

    输入包括键盘输入,鼠标右键粘贴输入等,如果要处理那么都要考虑全了。且要在输入的同时进行处理。
    且对一个单元格来说,它的按键及鼠标处理基本上都要在列的编辑控件上操作。
    除非你自定义DataGridView的列了。