Speaking in Code

Monday, April 17, 2006

Scope, ListBox Population, Headaches

I just spent oh, 5 hours or so tracking down the cause of the following problem:
Populating a vb.net 2005 listbox with Person objects, the listbox appeared correctly, but when I tried to manipulate (use SelectedItem) the list later, SelectedItem could return only the last entry.
What I finally learned is that the routine I used to fill the listbox with had a problem with variable scope.
I dimensioned the Person instance once and tried to use it for every new Person. When I moved the dimension to inside the While ... End While block, the behavior of the listbox became as expected. Ugh. Glad to be through that. I Hope this helps someone down the road.
Here is the code that works. Of particular interest is the location of the line
"Dim prsn as New Oxalis.Person"

Private Sub fill_existing_staff()
'fill the staff and task listboxes with any previously inserted values
'lookup the projectstaff table
Dim cmd As SqlCommand = New SqlCommand("spProjectStaff")
cmd.CommandType = CommandType.StoredProcedure
Dim con As New SqlConnection(m_SQLConn)

con.Open()
'filter on the selected ProjectID
cmd.Parameters.AddWithValue("@ProjectID", Me.TreeView1.SelectedNode.Tag.ToString)
cmd.Connection = con
'Clear any previous entries
Me.StaffIDListBox.Items.Clear()
'return the current values
Dim dtr As SqlDataReader = cmd.ExecuteReader()
'read them into the listbox
While dtr.Read()
Dim prsn As New Oxalis.Person
prsn.PersonID = dtr.Item(0)
prsn.Name = dtr.Item(1)

Me.StaffIDListBox.Items.Add(prsn)
Debug.Print("Person added: " & prsn.Name)
End While
dtr.Close()
End Sub