0

I have a Panel that has AutoScroll = true.

In that Panel is a series of TextBoxes. I should note that the TextBoxes 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 TextBoxes I mentioned earlier rely heavily on focus. Only the user should be able to remove focus from the TextBox by clicking somewhere else.

The TextBoxes 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 TextBoxes is focused?

Karlovsky120
  • 6,212
  • 8
  • 41
  • 94

1 Answers1

1

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));

Community
  • 1
  • 1
Keyur PATEL
  • 2,299
  • 1
  • 15
  • 41
  • Problem is that Textboxes aren't on the control, but are nested a few layers (4-5) down. Btw, it's `x.Focused()`, and I would add `break;` after `anyTextBoxFocused = true;`. – Karlovsky120 Sep 14 '16 at 03:19
  • 1
    Changed, thanks for spotting the Focused, added a break, and also hopefully provided help on how you can get even nested Textboxes. – Keyur PATEL Sep 14 '16 at 03:25
  • I managed to find clean way of keeping the references. But your answer is what I would have done if I didn't. – Karlovsky120 Sep 14 '16 at 03:28
  • If I may ask, what is the clean way you found? Did you declare a global array of textboxes and add to it every time you created a new one? Call it programmer's curiosity :) – Keyur PATEL Sep 14 '16 at 03:31
  • There was a spot in my class where I was adding TextBoxes parents to the panel. I added the parents to a list and used the list to go through them. – Karlovsky120 Sep 14 '16 at 03:53