限定输入框只能输入数字, TextBox的TextChanged事件调用

        /// <summary>
        /// 限定输入框只能输入数字, TextBox的TextChanged事件调用
        /// </summary>
        /// <param name="e">控件对象</param>
        /// <param name="strText">空间中原有的文本</param>
        /// <param name="isNegative">是否允许负数</param>
        /// <param name="isDecimal">是否允许小数</param>
        public void inputLimitNumber(ref object sender, string strNumType = "int")
        {
            try
            {
                Int64 isNum = 0;
                TextBox txt = (TextBox)sender;
                string strText = txt.Text = txt.Text.Trim();
                int focusIndex = txt.SelectionStart;

                if (!Int64.TryParse(strText, out isNum))
                {
                    for (int i = strText.Length - 1; i >= 0; i--)
                    {
                        if (!Int64.TryParse(strText.Substring(i, 1), out isNum))
                        {
                            strText = strText.Remove(i, 1);
                            focusIndex -= 1;
                        }
                    }
                }

                txt.Text = strText;
                if (focusIndex < 0)
                {
                    focusIndex = 0;
                }

                txt.Select(focusIndex, 0);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误信息", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
posted on 2020-01-17 17:10  幽冥20  阅读(347)  评论(0)    收藏  举报