我有后期绑定这个问题:我正在创建一个购物清单应用程序。我有一个名为Item
的班级,用于存储购物清单上商品的name
,price
,quantity
和description
。
我有一个名为ListCollection
的模块,它定义了Collection
个Item
个对象。我创建了一个Edit
表单,它会自动显示当前选中的ListCollection
项属性,但每当我尝试填充文本框时,它都会告诉我Option Strict
不允许后期绑定。
我可以采用简单的路线并禁用Option Strict
,但我更愿意弄清问题是什么,所以我知道以供将来参考。
我将在此处粘贴相关代码。 (后期绑定错误在EditItem.vb
。)
Item.vb代码:
' 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代码:
' 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代码:
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!
我尝试声明String
变量并为其分配Item
属性,我也尝试直接从List
项中获取值(不使用{{1}功能),这些都没有区别。
如何解决此问题?
答案 0 :(得分:2)
您必须将项目从“对象”转换为您的类型(“EditItem”)。
http://www.codeproject.com/KB/dotnet/CheatSheetCastingNET.aspx
编辑:
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
我在VB.NET中没有编写任何代码多年,我希望它没事。