C#递归遍历窗体所有textbox控件并设置textbox事件的方法

时间:2022-03-07 14:32:44

/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public virtual void SetTextBoxOnEnterStyle(object sender, EventArgs e)
{
    if (sender is TextBox)
    {
 TextBox tbox = sender as TextBox;
 if (!tbox.ReadOnly)
 {
     tbox.BackColor = Color.Yellow;
 }
    }
}

/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public virtual void SetTextBoxOnLeaveStyle(object sender, EventArgs e)
{
    if (sender is TextBox)
    {
 TextBox tbox = sender as TextBox;
 if (!tbox.ReadOnly)
 {
     tbox.BackColor = Color.White;
 }
    }
}
/// <summary>
///
/// </summary>
/// <param name="frm"></param>
public virtual void SetFormTextBoxControlStyle(Form frm)
{
    IterateControlsSetTextBox(frm.Controls);
}

/// <summary>
///
/// </summary>
/// <param name="ctls"></param>
public virtual void IterateControlsSetTextBox(Control.ControlCollection ctls)
{
    foreach (Control control in ctls)
    {
 if (control is TextBox)
 {
     (control as TextBox).Enter += new EventHandler(SetTextBoxOnEnterStyle);
     (control as TextBox).Leave += new EventHandler(SetTextBoxOnLeaveStyle);
 }

if (control.Controls.Count > 0)
 {
     IterateControlsSetTextBox(control.Controls);
 }
    }
}