How to cycle through all TextBox in a Form ?

  • Thread starter Thread starter fmarchioni
  • Start date Start date
F

fmarchioni

Hi all,
I need to highlight textbox in a Form when they are selected.
In order to do it I have added for each one a .GotFocus and .LostFocus
Event Handler....

textRS.GotFocus += new EventHandler(gotFocus_Event);
textName.GotFocus += new EventHandler(gotFocus_Event);
textSurname.GotFocus += new EventHandler(gotFocus_Event);
textAddress.GotFocus += new EventHandler(gotFocus_Event);

textRS.LostFocus += new EventHandler(lostFocus_Event);
textName.LostFocus += new EventHandler(lostFocus_Event);
textSurname.LostFocus += new EventHandler(lostFocus_Event);
textAddress.LostFocus += new EventHandler(lostFocus_Event);

I'd like to know how can I accomplish the same iterating through all
TextBoxes in the Form, so I can use this function in all Forms....
Thanks a lot
Francesco
 
public void HookupTextBoxes(Control.ControlCollection controls) {
foreach(Control control in this.Controls) {
if(control is TextBox) {
TextBox textBox = (TextBox) control;
textBox.GotFocus += new EventHandler(gotFocus_Event);
textBox.LostFocus += new EventHandler(lostFocus_Event);
} else {
HookupTextBoxes(control.Controls);
}
}
}

MainForm ctor, after InitializeComponent:
HookupTextBoxes(this);

I think that should do it.
 
public void HookUpTextBoxes(Form frm)
{
foreach( Control c in frm.Controls)
{
TextBox t = c as TextBox;
if( t != null )
{
t.GotFocus += new EventHandler(gotFocus_Event);
t.LostFocus += new EventHandler(lostFocus_Event);
}
}
}

This doesn't cater for panels, etc which may contain textboxes, but you can special case things like that - or just recurse in general

Regards

Richard Blewett - DevelopMentor
http://www.dotnetconsult.co.uk/weblog
http://www.dotnetconsult.co.uk

Hi all,
I need to highlight textbox in a Form when they are selected.
In order to do it I have added for each one a .GotFocus and .LostFocus
Event Handler....

textRS.GotFocus += new EventHandler(gotFocus_Event);
textName.GotFocus += new EventHandler(gotFocus_Event);
textSurname.GotFocus += new EventHandler(gotFocus_Event);
textAddress.GotFocus += new EventHandler(gotFocus_Event);

textRS.LostFocus += new EventHandler(lostFocus_Event);
textName.LostFocus += new EventHandler(lostFocus_Event);
textSurname.LostFocus += new EventHandler(lostFocus_Event);
textAddress.LostFocus += new EventHandler(lostFocus_Event);

I'd like to know how can I accomplish the same iterating through all
TextBoxes in the Form, so I can use this function in all Forms....
Thanks a lot
Francesco


--
No virus found in this incoming message.
Checked by AVG Anti-Virus.
Version: 7.0.300 / Virus Database: 265.7.1 - Release Date: 19/01/2005



[microsoft.public.dotnet.languages.csharp]
 
Back
Top