Okay, someone explain this one. I retrieve the environment variable USERNAME and assign it to a string variable. I can even show it in a MSGBOX and it shows "Owner". In my code I want to assign the value to a text box when it gets focus. It does it, but it flashes blue and then disappears and the text box appears blank, but if I save the record and go back to it? The value is there.
Help?

Dim strUserName As String
        strUserName = Environment.GetEnvironmentVariable("USERNAME")
        MsgBox(strUserName)
        LogInNameTextBox.Text = Convert.ToString(strUserName)

You didn't post the actual code you're using, right?

You're probably doing something like this

Private Sub TextBox1_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.GotFocus
    '
    Dim strUserName As String
    strUserName = Environment.GetEnvironmentVariable("USERNAME")
    TextBox1.Text = Convert.ToString(strUserName)
End Sub

Change it to

Private Sub TextBox1_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.GotFocus
  '
  Dim strUserName As String
  strUserName = Environment.GetEnvironmentVariable("USERNAME")
  TextBox1.Text = strUserName
  TextBox1.SelectionStart = 0
  TextBox1.SelectionLength = 0

End Sub

and remove Convert.ToString(). You're converting a string to a string, no need to do that.

Thanks for the tip but it didn't work. The field it fails to initialize is bound to a database table. When I try it on a plain text box, it works without the .select stuff.

Any thoughts?

Thanks,
Bill P.

Ok. How's Environment.GetEnvironmentVariable("USERNAME") related to the db table? Do you read some value to the textbox, then change it in GotFocus and save back to DB?

I've had a similar problem and it ended up a variable scope situation. Try this as a test...
Create a global variable (I'm note sure where would be appropriate in your code, if the is a generic Form put it in):

Public Class Form1
        Public userName As New StringBuilder

Then, in the sub where you retrieve USERNAME, instead of using a pointer to it (assigning it to a string), make a copy of it in the Public StringBuilder: userName = userName.Append(Environment.GetEnvironmentVariable("USERNAME")) Then use userName.ToString when you want this data. There are some problems with re-using StringBuilder Class as there is no Clear method (it is easy to write your own). If this solves the problem let us know!

This article has been dead for over six months. Start a new discussion instead.