2011-11-27 22 views
1

我有迟到绑定的问题:我正在创建一个购物清单应用程序。我有一个名为Item的类,它存储购物清单上的一个项目的nameprice,quantitydescription后期绑定和选项严格

我有一个名为ListCollection的模块,它定义了一个CollectionItem对象。我创建了一个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项目中获取值(不使用Get函数),并且这些都没有什么不同。

我该如何解决这个问题?

回答

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什么,我希望这是所有权利。

+0

我不完全确定我会这样做(或如何)。你介意为我澄清一下吗?我读过你的链接,但对我来说这是希腊文。 –

+0

是的!那确实有效。 :)事实上,经过一段时间后,结果变得更加简单 - 不是将列表创建为对象并将其作为项目进行投射,而只是将其创建为项目并完全绕过了投射。瞧! *而且*我在这个过程中学到了一些东西。非常感谢。 –

+0

我很想帮你:)。这是面向对象的基本方面之一。它被称为“拳击和拆箱”。我建议你研究它。 – TcKs