将OnLeave函数添加到140个对象?

时间:2014-06-19 09:24:38

标签: c# winforms forms visual-studio-2010 visual-studio

我有一个包含大约140个numericUpDown元素的窗体,希望所有这些元素都能执行此操作:

private void numericUpDown_B1_RS_LS_Leave(object sender, EventArgs e)
{
    if (numericUpDown_B1_RS_LS.Value < 1 || numericUpDown_B1_RS_LS.Value > 6)
    {
        numericUpDown_B1_RS_LS.BackColor = Color.Red;
    }
    else
    {
        numericUpDown_B1_RS_LS.BackColor = Color.White;
    }
}

除了手动向表单添加140个函数之外,还有更舒服的方法吗?

3 个答案:

答案 0 :(得分:0)

您不应该为相同的代码编写多个函数。相反,您可以只创建一个函数并将其分配给numericUpDown元素的事件方法,即“UpDown”事件。

因此,无论何时触发任何元素的“UpDown”事件,都将执行相同的功能。并且,只要您想为不同的元素编写不同的方法,那么请在您的方法中考虑

Method(object sender, EventArguments e)

sender是updownElement类型的实际发送方对象,该代码仅针对该特定对象执行。

您可以使用循环来迭代所有140个元素,并将此函数分配给“UpDown”元素。

答案 1 :(得分:0)

假设您希望对表单上的所有NUD使用相同的方法,则可以执行此操作:

public Form1()
{
    InitializeComponent();
    foreach (Control ctl in this.Controls)
        if (ctl.GetType() == typeof(NumericUpDown) ) ctl.Leave += numericUpDown_Leave;

}


private void numericUpDown_Leave(object sender, EventArgs e)
    {
        NumericUpDown NumericUD =  (NumericUpDown) sender ;
        if (NumericUD.Value < 1 || NumericUD.Value > 6)
        {
            NumericUD.BackColor = Color.Red;
        }
        else
        {
            NumericUD.BackColor = Color.White;
        }
    }

如果NUD没有直接位于表单上,您可以轻松地遍历另一个容器的Controls集合,例如Panel或GroupBox。如果某些NUD应该从该行为中排除,您可以用某种方式标记它们,可能在它们的标签或名称中,并在添加其处理程序之前检查它们。

答案 2 :(得分:0)

也许你可以编写一个静态方法来递归地处理事件处理程序的添加,例如:

    private void frmMain_Load(object sender, EventArgs e)
    { 
         AddHandleNumericUpdownLeave(this);
    }

    public static void AddHandleNumericUpdownLeave(Control theContrl)
    {
        if (theContrl.Controls != null && theContrl.Controls.Count > 0)
        {
            foreach (Control cControl in theContrl.Controls)
            {
                AddHandleNumericUpdownLeave(cControl);
            }
        }
        else
        {
            NumericUpDown nudCtrl = theContrl as NumericUpDown;
            if (nudCtrl != null)
            {
                nudCtrl.Leave += (object senderT, EventArgs eT) =>
                {
                    var tmpCtrl = senderT as NumericUpDown;
                    if (tmpCtrl != null)
                    {
                        if (tmpCtrl.Value < 1 || tmpCtrl.Value > 6)
                        {
                            tmpCtrl.BackColor = Color.Red;
                        }
                        else
                        {
                            tmpCtrl.BackColor = Color.White;
                        }
                    }
                }
            }
        }
    }

但如果表单中有太多控件,这可能会很昂贵......