我的dataGridView  控件要实现这样的功能:
只允许输入浮点数,如果输入的不符合规则,那么我就把该单元格原来的内容有赋给该单元格,也就是不让错误的输入生效。
代码如下:        private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            float d = 0.0F;
            string tmp = "";
            dataGridView1.Rows[e.RowIndex].ErrorText = string.Empty;            int tmp1 = dataGridView1.CurrentCell.RowIndex;
            int tmp2 = dataGridView1.CurrentCell.ColumnIndex;                tmp = dataGridView1.Rows[tmp1].Cells[tmp2].Value.ToString();
                
                    if (dataGridView1.Rows[e.RowIndex].IsNewRow) { return; }
                    if (!float.TryParse(e.FormattedValue.ToString(),
                        out d) || d < 0 || d >= 300)
                    {
                        dataGridView1.Rows[tmp1].Cells[tmp2].Value = tmp;
                        dataGridView1.Rows[e.RowIndex].ErrorText = "第" + (tmp2 + 1).ToString() + "列输入有误!";
                    }
                
            
        }上边的代码结果是这样的:如果我输入的是一个无效的内容,那么错误内容还是会显示。

解决方案 »

  1.   

    private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)  
      {  
      double d= 0.0;  
      dataGridView1.Rows[e.RowIndex].ErrorText = string.Empty;  
      if(dataGridView1.Columns[e.ColumnIndex].DataPropertyName == "")  
      {  
      if(!double.TryParse(e.FormattedValue.ToString(),out d) )  
      {  
      dataGridView1.Rows[e.RowIndex].ErrorText = "输入有误!";  
      e.Cancel = true;  
      }  
      }  
      }