Class Problem

Cyrus

Newcomer
Joined
Jul 25, 2003
Messages
11
Hey guys,

(I hope this is the right category for this topic)

I have some problems with Classes! I wrote the following test class:


Visual Basic:
Public Class TestClass

  Public Structure structWord
     Public ID As Integer
     Public Text As String
  End Structure

  Public Words() As structWord

  Public Sub New()
     ReDim Words(-1)

     AddWord("Test1")
     AddWord("Test2")
     AddWord("Test3")
  End Sub

  Private Sub AddWord(ByVal Text As String)
     Dim t As Integer

     t = UBound(Words) + 1
     ReDim Words(t)
     Words(t).ID = t
     Words(t).Text = Text
  End Sub

End Class


I also have a Form and a Button in my TestProject, when pressing the button, this happens:

Visual Basic:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
   Dim haha As New TestClass
   MsgBox(haha.Words(0).Text)
End Sub


Problem:
The MessageBox shows an empty string (It should display "Test1", shouldn't it? Has somebody an idea why?

(Edit: and has somebody an idea how to post better readable VB code in here? Edit: ahhh, just found it)
 
Last edited:
well i just did it this way ( not declaring the structure as an array , rather the text / id )
Visual Basic:
Public Class Class1

    Public Structure structwrd
        Public ID() As Integer
        Public Text() As String
    End Structure

    Public Words As New structwrd()

    Public Sub AddIt()
        Dim arr() As String = {"Test1", "Test2", "Test3"}
        AddWord(arr)
    End Sub

    Public Sub AddWord(ByVal Text() As String)
        ReDim Words.ID(UBound(Text))
        ReDim Words.Text(UBound(Text))
        Dim x As Integer
        For x = LBound(Text) To UBound(Text)
            Words.Text(x) = Text(x)
        Next
    End Sub


End Class
Visual Basic:
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim haha As New Class1()
        haha.AddIt()
        MessageBox.Show(haha.Words.Text(0))
    End Sub
hope that helps.
 
I think the problem in the first bit of code is that you were using Redim not Redim Preserve, thus it was clearing the array each time.
 
Argh %§&!?

You're right!
i just forgot "perserve", thank you!!

(by the way, why did you move this post? wasn't that a syntax related question?)
 
Back
Top