动态生成控件 并设置只能输入数字 和小数点

1.在窗体里加入10个输入控件并把他们放在groupBox里

2.在 Load事件里输入代码:

  private void Form1_Load(object sender, EventArgs e)
        {
            int count = this.Controls.Count;

            foreach (Control item in groupBox1.Controls)
            {
                if (item is TextBox)
                {
                    // TextBox box = (TextBox)item;
                    TextBox box = item as TextBox;
                    box.Text = "";
                }

            }

3.设置一个自己的控件:

4.在控件小闪电里找KeyPress事件 并加入代码:

 private void userControl11_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (((int)e.KeyChar < 48 || (int)e.KeyChar > 57) && (int)e.KeyChar != 8 && (int)e.KeyChar != 46)
                e.Handled = true;
            //小数点的处理。
            if ((int)e.KeyChar == 46)                           //小数点
            {
                if (textBox1.Text.Length <= 0)
                    e.Handled = true;   //小数点不能在第一位
                else
                {
                    float f;
                    float oldf;
                    bool b1 = false, b2 = false;
                    b1 = float.TryParse(textBox1.Text, out oldf);
                    b2 = float.TryParse(textBox1.Text + e.KeyChar.ToString(), out f);
                    if (b2 == false)
                    {
                        if (b1 == true)
                            e.Handled = true;
                        else
                            e.Handled = false;

                    }

原文地址:https://www.cnblogs.com/wuayn/p/8821279.html