Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

hi

i need to change the background colour of a control (say textbox for a example) when it has gotfocus and change back to the original colour when lostfocus. (in a vb.net windows application)

 

 

 

i know i can write subs for each and every control as follows

 

 

Private Sub TextBox1_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.LostFocus

 

End Sub

 

 

 

Private Sub TextBox1_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.GotFocus

 

End Sub

 

 

 

but i don't want to do this since i have too much of controls in my form

do i have any other option?

  • Administrators
Posted

You could dynamically wire up the event handlers in your form load event like...


Private Sub control_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs)

	Dim c As Control = DirectCast(sender, Control)
	'handle the lost focus here
End Sub

Private Sub control_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs)
	Dim c As Control = DirectCast(sender, Control)
	'handle got focus here
End Sub

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
	For Each c As Control In Me.Controls
		AddHandler DirectCast(c, Control).GotFocus, AddressOf control_GotFocus
		AddHandler DirectCast(c, Control).LostFocus, AddressOf control_LostFocus
	Next
End Sub

Posting Guidelines FAQ Post Formatting

 

Intellectuals solve problems; geniuses prevent them.

-- Albert Einstein

Posted

hi PlausiblyDamp

 

Thank you very much

it is working fine

 

but now my problem is when i click on a button it's changing the colour of the button too .

 

how can i prevent this problem?

Posted

Don't know VB but here:

For Each c As Control In Me.Controls
		AddHandler DirectCast(c, Control).GotFocus, AddressOf control_GotFocus
		AddHandler DirectCast(c, Control).LostFocus, AddressOf control_LostFocus
	Next

 

you have to check wether the control is a button and only if it isn't add the event handler.

in c#:

foreach (Control c in this.Controls)
{
    if (!(c is Button))
    {
       //Add Handlers here
    }
}

Debug me...

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...