How to globally trigger function whenever form's controls lose focus?

K

Karen

Hi,

We migrated an old VB6 app to .NET. It's an order entry application,
and whenever a control loses focus we call a function to recalcuate
the totals. This works fine, but the same function is called from
within nearly 100 controls!.

Does anyone know how to do this at the form level in .NET..

psuedo-code

if control type textbox (listbox, checkbox)...etc loses focus. then
call function
end if

Thanks,
Karen
 
H

Herfried K. Wagner [MVP]

* Karen said:
We migrated an old VB6 app to .NET. It's an order entry application,
and whenever a control loses focus we call a function to recalcuate
the totals. This works fine, but the same function is called from
within nearly 100 controls!.

Does anyone know how to do this at the form level in .NET..

psuedo-code

if control type textbox (listbox, checkbox)...etc loses focus. then
call function
end if

Loop through the controls and add a common handler by using the
'AddHandler' keyword (see help).
 
J

Jeremy Todd

Karen said:
Hi,

We migrated an old VB6 app to .NET. It's an order entry application,
and whenever a control loses focus we call a function to recalcuate
the totals. This works fine, but the same function is called from
within nearly 100 controls!.

Does anyone know how to do this at the form level in .NET..

psuedo-code

if control type textbox (listbox, checkbox)...etc loses focus. then
call function
end if

You can do this by attaching an event handler to each control's
LostFocus event as it is added to the form. In VB, the code (which should
appear in the Form's code section) would be something like:

Protected Overrides Sub OnControlAdded(ByVal e As ControlEventArgs)
MyBase.OnControlAdded(e)

Dim controlType As Type = e.Control.GetType

Select Case True
Case controlType Is GetType(TextBox), _
controlType Is GetType(ListBox), _
[etc. etc.]
AddHandler e.Control.LostFocus, AddressOf MyMethod
End Select
End Sub

Protected Overrides Sub OnControlRemoved(ByVal e As ControlEventArgs)
MyBase.OnControlRemoved(e)

Dim controlType As Type = e.Control.GetType

Select Case True
Case controlType Is GetType(TextBox), _
controlType Is GetType(ListBox),
[etc. etc.]
RemoveHandler e.Control.LostFocus, AddressOf MyMethod
End Select
End Sub

Private Sub MyMethod(ByVal sender As Object, ByVal e As EventArgs)
' Do whatever you need to
End Sub

I hope this is what you're looking for!
Jeremy
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top