1

我在后期绑定时遇到了这个问题:我正在创建一个购物清单应用程序。我有一个名为的类Item,它存储杂货清单上某项的namepricequantity和。description

我有一个名为的模块ListCollection,它定义了一个Collection对象Item。我创建了一个Edit表单,它将自动显示当前选定的ListCollection项目属性,但是每当我尝试填充文本框时,它都会告诉我Option Strict不允许后期绑定。

我可以采取简单的方法并禁用Option Strict,但我更愿意找出问题所在,以便我知道以供将来参考。

我将在此处粘贴相关代码。(后期绑定错误在EditItem.vb。)

项目.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项目中获取值(不使用Get函数),但这些都没有任何区别。

我该如何解决这个问题?

4

1 回答 1

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 中编写任何代码,我希望一切都好。

于 2011-11-27T03:50:08.800 回答