在cellcontentclick事件中用正则表达式判断是否为数字

解决方案 »

  1.   

    private DataGridViewTextBoxEditingControl EditCell;void DataGideView_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
    {
    EditCell = (DataGridViewTextBoxEditingControl)e.Control;
    EditCell.SelectAll();
    EditCell.KeyPress += new KeyPressEventHandler(Cells_KeyPress);
    }void Cells_KeyPress(object sender, KeyPressEventArgs e)
    {
    if (!Char.IsNumber(e.KeyChar) && !Char.IsPunctuation(e.KeyChar) && !Char.IsControl(e.KeyChar))
    {
    e.Handled = true;
    }
    }
      

  2.   

    由于datagridview不响应键盘事件,直接控制有些困难,但输入完毕后控制还是可以的,在CellParsing事件中这么写
      private void dataGridView1_CellParsing(object sender, DataGridViewCellParsingEventArgs e)

    DataGridView dgv = (DataGridView)sender; if (dgv.Columns[e.ColumnIndex].Name == "要控制的列名")//如果不是一列就继续加条件好了 {
     for (int i = 0; i < e.Value.ToString().Length; i++)
     {  string f = e.Value.ToString().Substring(i, 1).ToString().Trim();  if (f != "1" && f != "2" && f != "3" && f != "4" && f != "5" && f != "6" && f != "7" && f != "8" && f != "9" && f != "0" && f != ".")  {
    e.Value = "";//如果不是数字,直接清空
      }
     }
    }
     e.ParsingApplied = true;
    }