DataGridView单元格只输入小数或整数

来源:互联网 发布:隔音窗帘 知乎 编辑:程序博客网 时间:2024/05/19 19:58

         本来是用msdn上的提供的重绘的DataGridViewNumbericUpDown组件,但是其中各种异常也解决不了,所以只能用笨办法了。

        首先在你的DataGridView中添加事件:

       private voidDataGridView_EditingControlShowing(object sender,DataGridViewEditingControlShowingEventArgs e)

        {

            if (DataGridView.CurrentCell ==null)

            {

                return;

            }

            int index =DataGridView.CurrentCell.ColumnIndex;

            TextBox tx = e.Control as TextBox;

            if (index == 3)

            {

                   tx.KeyPress += newKeyPressEventHandler(control_KeyPress);

             }

       }

      单元格作为TextBox控件时加载的事件:

          //单元格只能输入小数。

        protected void control_KeyPress(objectsender, KeyPressEventArgs e)

        {

                    //该事件用于控制只接收数字、小数点和退格键输入,别且不能输入两个小数点。

                   Regex rg = new Regex(@"\.");

                string textBoxStr =((TextBox)sender).Text;

                MatchCollection mc =rg.Matches(textBoxStr);

                int textBoxCount = mc.Count;

               //允许输入数字,小数点,退格键,不允许输入大于18为的数字,不允许输入两个小数点

                if ((int)e.KeyChar >= 48&& (int)e.KeyChar <= 57 || (int)e.KeyChar == 8 || e.KeyChar == '.')//只能输入0-9数字和BackSpace

                {

                    if (textBoxStr.Length <18 && textBoxCount < 2)

                    {

                        if (e.KeyChar != '.' ||textBoxCount == 0)

                        {

                            e.Handled = false;

                        }

                        else

                        {

                            e.Handled = true;

                        }

                    }

                    else

                    {

                        e.Handled = true;

                    }

                }

                else

                {

                    e.Handled = true;

                }

        }

另外提供只输入整数的事件源码:

        private void IntBool_KeyPress(objectsender, KeyPressEventArgs e)

        {

            if ((int)e.KeyChar >= 48&& (int)e.KeyChar <= 57 && textBox.Text.Length < 18 ||(int)e.KeyChar == 8) //只能输入0-9数字和BackSpace

            {

                e.Handled = false;

            }

            else

            {

                e.Handled = true;

            }

        }

 


0 0