Groups | Blog | Home
all groups > dotnet windows forms controls > may 2005 >

dotnet windows forms controls : Set focus to a UserControl added on a Form


Ruslan
5/25/2005 12:00:00 AM
Hello





I have a form with a panel. In this panel a new UserControl is added:



UserControl1 c = new UserControl1();

c.Location = new Point(10, 10) ;

panel1.Controls.Add(c);



This UserControl1 has some textboxes. I want to set focus to the first
textbox from the UserControl. The Focus() method doesn't work. How can it be
done?



Thanks,



Ruslan


Ivor
5/26/2005 1:48:53 AM
I think the problem is that you need to set the focus to the
UserControl on the panel, and not just the panel.
Certainly this.panel1.Controls[0].Focus() (or whatever control index
for your userControl) works for me.
If you don't know the control index, then you might have to enumerate
over the controls to find the right one...
A more comprehensive example is...

foreach( Control indexControl in this.panel1.Controls )
{
// Find the User Control on the panel
if ( indexControl.Name.ToLower() == "usercontrol1" )
{
UserControl1 myUserControl = (UserControl1)indexControl;
foreach( Control innerIndexControl in myUserControl.Controls )
{
// Find the right text box on the User Control
if ( innerIndexControl.Name.ToLower() == "textbox1" )
{
innerIndexControl.Focus();
}
}
}
}

Not sure if you know this, but you might be able to solve the problem
with tab order.
If the panel has a tab order of 0, and the textbox you want to have the
focus has a tab order of 0 for the user control, that textbox will have
the focus by default when the form is loaded.
Gerd Klevesaat
5/26/2005 8:25:02 AM
Hi,

you also have to make sure the the user control, in turn, sets the focus to
the required text box. This will be done automatically for you based on the
tab order.

Define the tab order in your user control (for instance, doing it
interactievly using TabOrder from view menu or by changing the tab index in
the properties view).
After the tab order has been set up, the Focus() method called on the user
control should work and set the focus to the control with lowest tab index.

HTH,
Gerd
AddThis Social Bookmark Button