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

本文详细介绍了如何在DataGridView中自定义输入验证,确保输入仅包含整数或小数,并限制输入长度不超过18位,避免非法输入影响数据准确性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

         本来是用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;

            }

        }

 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值