I have this problem with late binding: I am creating a grocery list application. I have a class named Item
which stores the name
, price
, quantity
, and description
of an item on the grocery list.
I have a module named ListCollection
which defines a Collection
of Item
objects. I have created an Edit
form which will automatically display the currently selected ListCollection
item properties, but whenever I attempt to fill the text boxes, it tells me that Option Strict
disallows late binding.
I COULD take the easy route and disable Option Strict
, but I'd prefer to figure out what the problem is so I know for future reference.
I shall paste pertinent code here. (Late binding error is in EditItem.vb
.)
Item.vb code:
' Member variables:
Private strName As String
' Constructor
Public Sub New()
strName = ""
' Name property procedure
Public Property Name() As String
Get
Return strName
End Get
Set(ByVal value As String)
strName = value
End Set
End Property
ListCollection.vb code:
' Create public variables.
Public g_selectedItem As Integer ' Stores the currently selected collection item.
' Create a collection to hold the information for each entry.
Public listCollection As New Collection
' Create a function to simplify adding an item to the collection.
Public Sub AddName(ByVal name As Item)
Try
listCollection.Add(name, name.Name)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
EditItem.vb code:
Private Sub EditItem_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
' Set the fields to the values of the currently selected ListCollection item.
txtName.Text = ListCollection.listCollection(g_selectedItem).Name.Get ' THIS LINE HAS THE ERROR!
I have tried declaring a String
variable and assigning the Item
property to that, and I have also tried grabbing the value directly from the List
item (not using the Get
function), and neither of these made a difference.
How can I fix this problem?
You must cast the item from "Object" to your type ("EditItem").
http://www.codeproject.com/KB/dotnet/CheatSheetCastingNET.aspx
EDIT:
Private Sub EditItem_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
' getting the selected item
Dim selectedItem As Object = ListCollection.listCollection(g_selectedItem)
' casting the selected item to required type
Dim editItem As EditItem = CType(selectedItem, EditItem)
' setting value to the textbox
txtName.Text = editItem.Name
I didn't code anything in VB.NET for years, I hope it is all right.