0

I have a form to add a new client to a database. Built in vb.net 2019 Windows Forms. I want to accomplish 2 things:

  1. When a user enters a textbox, change textbox backcolor to cyan and forecolor to navy to highlight that the user is editing that field.
  2. When a user leaves a textbox, revert colors back to original but also update the existing text to uppercase.

I have this accomplished already, but, I'm wondering if my method is making unnecessary steps or whether or not it's best practice to add this to the enter and leave event for every single textbox.

Private Sub TextBox1_Enter(sender As Object, e As EventArgs) Handles TextBox1.Enter
        TextBox1.BackColor = Color.Cyan
        TextBox1.ForeColor = Color.Navy
    End Sub

    Private Sub TextBox1_Leave(sender As Object, e As EventArgs) Handles TextBox1.Leave
        TextBox1.BackColor = Color.White
        TextBox1.ForeColor = Color.Black
        TextBox1.Text = TextBox1.Text.ToUpper
    End Sub
    Private Sub TextBox2_Enter(sender As Object, e As EventArgs) Handles TextBox2.Enter
        TextBox2.BackColor = Color.Cyan
        TextBox2.ForeColor = Color.Navy
    End Sub

    Private Sub TextBox2_Leave(sender As Object, e As EventArgs) Handles TextBox2.Leave
        TextBox2.BackColor = Color.White
        TextBox2.ForeColor = Color.Black
        TextBox2.Text = TextBox2.Text.ToUpper
    End Sub

I'm not asking for you to do the work for me- just point me in the right direction, so please don't close this question unless necessary. Legitimately curious if this method is best practice or if there's a more efficient way of handling this.

  • 1
    You might find [this post](https://stackoverflow.com/q/1303145/62576) helpful. `sender` has meaning, and you can avoid all of the repetitive code by using it. – Ken White Oct 15 '21 at 21:25
  • 4
    [Code Review](https://codereview.stackexchange.com/) is a better fit for questions about reviewing _working_ code in most cases. Anyway, one thing you can improve is to have only two event handlers (e.g., `TextBoxes_Enter` and `TextBoxes_Leave`) and have then handle the events for both/all TextBoxes. You can achieve that using the `Handles` clause (e.g., `Handles TextBox1.Enter, TextBox2.Enter,...`) or using `AddHandler`. Then, inside the event handlers, you can cast `sender` to a TextBox to access the specific TextBox that triggered the event (e.g., `Dim txtBox = DirectCast(sender, TextBox)`) – 41686d6564 stands w. Palestine Oct 15 '21 at 21:26
  • Posting here because I can no longer post this to the now-deleted SQL question from a moment ago. You should know that because of the way Sql Server handles indexes and type binding, there are some gotchas with the AddWithValue() function that can have big performance costs. You're very often better off choosing an SqlParameterCollection.Add() overload where you manually set the database data type and length for your parameters. – Joel Coehoorn Oct 22 '21 at 22:04

0 Answers0