Karlovsky120 Karlovsky120 - 2 months ago 39
C# Question

To focus or not to focus

I have a

Panel
that has
AutoScroll = true
.

In that
Panel
is a series of
TextBox
es. I should note that the
TextBox
es aren't on the
panel
directly but are nested several levels (about 4-5).

Now, the scrolling with my mouse wheel works only if the panel has focus, naturally. I can use
Focus()
within
mouseEnter
event to make sure the panel has focus.

However, the
TextBox
es I mentioned earlier rely heavily on focus. Only the user should be able to remove focus from the
TextBox
by clicking somewhere else.

The
TextBox
es are created dynamically and would make for a very messy code to keep an array of them, or any type of reference to check if they have focus. Not to mention that there could be a lot of them.

How do I give the focus to the
Panel
, but only if none of the
TextBox
es is focused?

Answer

You don't need to keep an array of the dynamically created Textboxes, you can get the array using:

bool anyTextBoxFocused = false;
foreach (Control x in this.Controls)
{
  if (x is TextBox && x.Focused)
  {
       anyTextBoxFocused = true;
       break;
  }
}
if (!anyTextBoxFocused)
{
    //give focus to your panel
}

Edit

Based on How to get ALL child controls of a Windows Forms form of a specific type (Button/Textbox)?, even nested controls can be obtained using:

public IEnumerable<Control> GetAll(Control control,Type type)
{
    var controls = control.Controls.Cast<Control>();

    return controls.SelectMany(ctrl => GetAll(ctrl,type))
                              .Concat(controls)
                              .Where(c => c.GetType() == type);
}

then use it with:

var c = GetAll(this,typeof(TextBox));