2011-11-27 21 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