要注意的是:

在(一)中,注册TextChanged事件的代码和本例中,注册KeyPress的代码不一样。该代码如果不会写,可以通过在Form中,添加一个textbox的keypress事件,然后将代码COPY过来。

注册textchanged事件:

this.textBox1.TextChanged += new System.EventHandler(this.textBox1_TextChanged);

注册KeyPress事件:

   this.textBox1.KeyPress +=  new System.Windows.Forms.KeyPressEventHandler(this.textBox1_KeyPress);

全部原代码如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;

namespace WindowsControlLibrary1
{
    public partial class UserControl1 : UserControl
    {
        public UserControl1()
        {
            InitializeComponent();
        }

        private void UserControl1_Load(object sender, EventArgs e)
        {
            this.textBox1.KeyPress +=  new System.Windows.Forms.KeyPressEventHandler(this.textBox1_KeyPress);


        }
        private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
        {

            int ch = e.KeyChar;
            if (((ch >= 48) && (ch <= 57) || ch == 8 || ch == 13) == false)
            {
                e.Handled = true;

            }

        }


    }
}

 

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/xjzdr/archive/2008/02/05/2084126.aspx