简体   繁体   English

如何将相似的事件处理程序添加到多种形式? IE按键事件到多个文本框

[英]How to add similar event handlers to multiple forms? I.E. keypressed event to multiple textboxes

I've followed this guide 我已遵循本指南

How do I make a textbox that only accepts numbers? 如何制作仅接受数字的文本框?

The method provided limits the characters we can input on the box 提供的方法限制了我们可以在框中输入的字符

private void textBox18_KeyPress_1(object sender, KeyPressEventArgs e)
    {
         if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) &&
            (e.KeyChar != ','))
        {
            e.Handled = true;
        }

        // only allow one decimal point
         if ((e.KeyChar == ',') && ((sender as TextBox).Text.IndexOf(',') > -1))
         {
             e.Handled = true;
         }
    }

it's working very well, but there's a catch, i have to add the event handler to 100+ text boxes. 它工作得很好,但是有一个陷阱,我必须将事件处理程序添加到100多个文本框中。 Is there a simpler way to do this? 有没有更简单的方法可以做到这一点? Since it envolves both the designer.cs and the cs. 由于它包含了designer.cs和cs。

I'm working on winform, visual c# 2010 express edition 我正在开发Winform,Visual C#2010 Express Edition

You could simply do this in the FormLoad method: 您可以简单地在FormLoad方法中执行此操作:

textBox19.KeyPress += textBox18_KeyPress_1;
textBox20.KeyPress += textBox18_KeyPress_1;
textBox21.KeyPress += textBox18_KeyPress_1;
textBox22.KeyPress += textBox18_KeyPress_1;
textBox23.KeyPress += textBox18_KeyPress_1;
// etc
textBox999.KeyPress += textBox18_KeyPress_1;

Rename your current textBox18_KeyPress_1 to something more descriptive. 将您当前的textBox18_KeyPress_1重命名为更具描述性的名称。

eg. 例如。 GenericTextBoxKeyPress

Then, in the constructor (after InitComponents) or Form Load, you may add these events to your textboxes one by one or using a loop. 然后,在构造函数中(在InitComponents之后)或在Form Load中,可以将这些事件一个接一个地添加或添加到循环中。

//One by one
textBox1.KeyPress += GenericTextBoxKeyPress;
textBox2.KeyPress += GenericTextBoxKeyPress;
textBox3.KeyPress += GenericTextBoxKeyPress;

//All TextBoxes in your form
foreach(var textbox in this.Controls.OfType<TextBox>())
{
    textbox.KeyPress += GenericTextBoxKeyPress;
}

Alternatively , you could create a class that implements TextBox and override the OnKeyPress behavior. 或者 ,您可以创建一个实现TextBox的类并重写OnKeyPress行为。 Then, change all your TextBoxes to use this new class. 然后,更改所有TextBoxes以使用此新类。

using System.Windows.Forms;

namespace MyApplication
{
    class MyTextBox : TextBox
    {
        protected override void OnKeyPress(KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) &&
            (e.KeyChar != ','))
            {
                e.Handled = true;
            }

            // only allow one decimal point
            if ((e.KeyChar == ',') && Text.IndexOf(',') > -1)
            {
                e.Handled = true;
            }
            base.OnKeyPress(e);
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM