简体   繁体   English

如何限制datagridview单元格中引入的数字?

[英]How I can limit the introduced digits in the cell of the datagridview?

I want to create a datagridview that only accept numbers (Integers or doubles). 我想创建一个只接受数字(整数或双精度)的datagridview。 When the number is double, I only want to save 2 digits after the point. 当数字加倍时,我只想在点后保存2位数。 (Eg 1.22) and automatically change the cell. (例如1.22)并自动更改单元格。 I create an event to make this. 我创建了一个事件来做到这一点。

I was able to get a working event but when I put the number with 2 digits after the point, the last digit doesn't appear in the cell and the cell change. 我能够得到一个工作事件但是当我在该点之后输入2位数字时,最后一位数字不会出现在单元格中并且单元格会发生变化。 When I'm debugging with a breakpoint in the line “dgvDatos[column, row].Value = txtInCell;” . 当我在“dgvDatos [column,row] .Value = txtInCell;”行中使用断点进行调试时。 The variable txtInCell (is used to see what is written in the cell ) has the correct/complete value . 变量txtInCell(用于查看单元格中写入的内容)具有正确/完整的值。

   void dText_KeyPress(object sender, KeyPressEventArgs e)
   {           

        bool dot;
        if (txtInCell.Contains(".") == true)
            dot = true;
        else
            dot = false;
        //Only accept numbers
        if (Char.IsDigit(e.KeyChar) || e.KeyChar == '.' || e.KeyChar == '-')
        {
            if (e.KeyChar == '.')
                if (!dot)
                {
                    txtInCell += e.KeyChar;
                    e.Handled = false;
                }
                else
                    e.Handled = true;
            else
                txtInCell += e.KeyChar;
            if (txtInCell.Contains("."))
            {
                int row = dgvDatos.CurrentCell.RowIndex;
                int column = dgvDatos.CurrentCell.ColumnIndex;
                string[] elements = txtInCell.Split('.');
                if (elements[1].Length > 1)
                {
                    dgvDatos[column, row].Value = txtInCell;
                    dgvDatos.CurrentCell = this.dgvDatos[column + 1, row];
                }
            }
        }
        else if (Char.IsControl(e.KeyChar)) //Use backspace as control
        {
            if (e.KeyChar == '\b')
                txtInCell = txtInCell.Remove(txtInCell.Length - 1);
            e.Handled = false;
        }
        else
        {
            //all the other keys are disabled
            e.Handled = true;
        }

   }

Use validate event 使用验证事件

 dataGridView1.CellValidating += (s, eargs) => eargs.Cancel = !new Regex(@"^\d*(.\d|.\d\d)$").IsMatch(eargs.FormattedValue.ToString());

You can also give a tooltip about why you are not allowing the user to enter the value like you cannot enter more than two decimal digits etc you can also add some coloring flashing to add more spice 您还可以提供一个工具提示,说明为什么您不允许用户输入值,就像您不能输入两个以上的十进制数字等。您还可以添加一些着色闪烁以添加更多香料

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM