不同textBox的一个事件。 [英] One event for different textBox.

查看:92
本文介绍了不同textBox的一个事件。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好。



我的Form1中有7个textBox



textBox0

textBox1





textBox6



我的问题:



我为每个文本框都有一些事件(做同样的事情,但对于每个文本框):



Hello.

I have 7 textBox in my Form1

textBox0
textBox1
.
.
textBox6

my question:

I have some event for each textbox (doing exactly the same thing, but for each textBox):

private void textBox0_Leave(object sender, EventArgs e)
        {
            if (textBox0.Text == "")
            {
                textBox0.Text = "0";
            }
        }





有没有办法在这样的活动中这样做:



Is there a way to do this in one event like this:

private void textBox[FOR ALL]_Leave(object sender, EventArgs e)
        {
            if (textBox[FOR ALL].Text == "")
            {
                textBox[FOR ALL].Text = "0";
            }
        }

推荐答案

看看这里:如何:在运行时为Windows窗体创建事件处理程序 [ ^ ]。


不是在表单中处理这些事件,而是通过创建一个新类并从TextBox继承来创建自己的TextBox版本。然后,您可以自定义TextBox以执行您想要的操作,编译它并将它显示在ToolBox中。在那里,你只需将TextBox拖到你的表单上,并使用它代替标准的TextBox控件。
Instead of handling these events in the form, make your own version of the TextBox that does this by creating a new class and inheriting from TextBox. You can then customize the TextBox to do the things you want, compile it and it'll show up in the ToolBox. Once there, you simply drag that TextBox onto your form and use that in place of the standard TextBox control.


你可以这样做:



You can do something like this:

private void TextBox_event(Control ctl)
{
    foreach (Control c in ctl.Controls)
    {
        if (c.HasChildren)
            TextBox_event(c);
        else
        {
            if (c.GetType() != typeof (TextBox)) continue;
            c.Leave += TextBoxLeave;
        }
    }
}

private static void TextBoxLeave(Object sender, EventArgs e)
{
    var value = ((TextBox) sender).Text;
    if (value == "")
        ((TextBox) sender).Text = "0";
}


这篇关于不同textBox的一个事件。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆