ProgrammingRookie
ProgrammingRookie

Reputation: 53

Trouble with textboxes losing focus in Visual Basic .net

Recently I got an assignment to make a very basic Sudoku-game in Visual Basic. To make this I am using Visual Studio Ultimate 2013 Update 4 with the .NET Framework.

I have gotten to the point where I can check which one out of many textboxes has focus. With this also change the backgroundColor of the corresponding textbox. I have done this using this by using this method:

Private Sub TextBox_GotFocus() Handles TextBox1.GotFocus, TextBox2.GotFocus, TextBox3.GotFocus Me.ActiveControl.BackColor = Color.Aquamarine End Sub

To Color it back to white when any of the textboxes lost focus I used this:

Private Sub TextBox_LostFocus() Handles TextBox1.LostFocus, TextBox2.LostFocus, TextBox3.LostFocus Me.ActiveControl.BackColor = Color.White End Sub

Now My Questions Are:

  1. Why does the Application crash when I close it? And how do I fix this?

(It Gives a NullReferenceException when being closed)

  1. Is this even a proper way to accomplish what I want? Or is there something more efficient?

Upvotes: 0

Views: 2741

Answers (1)

Abdul Saleem
Abdul Saleem

Reputation: 10622

Add object, EventArgs as parameters.

;

The object will be the calling control which invokes the event.

Private Sub TextBox_GotFocus(sender As Object, e As EventArgs) Handles TextBox1.GotFocus, TextBox2.GotFocus, TextBox3.GotFocus
    CType(sender, TextBox).BackColor = Color.Aquamarine
End Sub

Private Sub TextBox_LostFocus(sender As Object, e As EventArgs) Handles TextBox1.LostFocus, TextBox2.LostFocus, TextBox3.LostFocus
    CType(sender, TextBox).BackColor = Color.White
End Sub

Upvotes: 4

Related Questions