Hi there,

I have been having some problems with my Visual Basic. In trying to figure that out, un-installing, and reinstalling, running virus scans, etc, I have lost a lot of my time to get this assignment done. I would just keep messing around with it and try to be further along, but I must move on. I have a group project as well and do not want to let my group down. So any help would be greatly appreciated.

We have a form application with 3 tab pages. The first tab page takes input for first name, last name, phone, birth month, and birth year in textboxes. This info is to be written to a file. The next tab page has a read button that then displays the data into a list box. The next tab page has a text box to take input for a birth month and then searches through the file and lists any file that matches that birth month.

The whole thing then needs to be serialized and deserialized.

I will post what I have so far. My first question is what do I need to do to get it to read into the listbox? I have tried multiple things. None work. After the issues I had with my visual basic, I don't know if for sure it is me, (most likely), or the software.
For the display, we are supposed to use an overloaded ToString method in another class.
Do I have to use an array?

Thank you so much for any help. I will likely have more questions as I go.

private void EnterFriendBtn_Click(object sender, EventArgs e)
        {
            friend.FName = Console.ReadLine();
            friend.LName = Console.ReadLine();
            friend.Phone = Console.ReadLine();
            friend.BMonth = Convert.ToInt32(Console.ReadLine());
            friend.BDay = Convert.ToInt32(Console.ReadLine());
            
            FileStream File = new FileStream("Friends.txt", FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
            StreamWriter writer = new StreamWriter(File);
            writer.WriteLine(ToString());

            writer.Close();
            File.Close();
        }

        private void ReadBtn_Click(object sender, EventArgs e)
        {
            FileStream File = new FileStream("Friends.txt", FileMode.OpenOrCreate, FileAccess.Read, FileShare.ReadWrite);
            StreamReader reader = new StreamReader(File);

            string recordIn;
            string[] fields;
         
            recordIn = reader.ReadLine();
            fields = recordIn.Split(',');

            friend.FName = fields[0];
            friend.LName = fields[1];
            friend.Phone = fields[2];
            friend.BMonth = Convert.ToInt32(fields[3]);
            friend.BDay = Convert.ToInt32(fields[4]);

            FriendList.Items.Add("{0,10}{1,10}{2,10}{3,4}{4,4}");
            while (!reader.EndOfStream)
            {
                FriendList.Items.Add(ToString());
            }

            reader.Close();
            File.Close();
           
        }

        private void FriendList_SelectedIndexChanged(object sender, EventArgs e)
        {
            
        }

        private void MonthEntryBtn_TextChanged(object sender, EventArgs e)
        {
            friend.BMonth = Convert.ToInt32(Console.ReadLine());
        }

        private void ReminderBtn_Click(object sender, EventArgs e)
        {

        }

        private void MonthFriend_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

Hi,

To read a TextFile into a ListBox you can do it like this:

// Load the ListBox from a file.
private void Form1_Load(System.Object sender, System.EventArgs e)
{
	try {
		string file_name = DataFile();
		System.IO.StreamReader stream_reader = new System.IO.StreamReader(file_name);

		ListBox1.Items.AddRange(Strings.Split(stream_reader.ReadToEnd(), Constants.vbCrLf));
		ListBox1.SelectedIndex = 0;
		stream_reader.Close();
	} catch (Exception exc) {
		// Report all errors.
		Interaction.MsgBox(exc.Message, MsgBoxStyle.Exclamation, "Read " + "Error");
	}
}

I doesn't use C# offen, but it should work thought.

Member Avatar for Unhnd_Exception

Heres a quick and dirty I put together.

May give you some ideas.

This does not check for any errors.

Public Class Form1

    Private FirstNames As String() = {"a", "b", "c", "d", "e"}
    Private LastNames As String() = {"z", "z", "x", "w", "v"}
    Private BirthMonths As Integer() = {1, 2, 1, 2, 3}

    Public Class Person
        Private fpFirstName As String
        Private fpLastName As String
        Private fpBirthMonth As Integer

        Public Property FirstName() As String
            Get
                Return fpFirstName
            End Get
            Set(ByVal value As String)
                fpFirstName = value
            End Set
        End Property

        Public Property LastName() As String
            Get
                Return fpLastName
            End Get
            Set(ByVal value As String)
                fpLastName = value
            End Set
        End Property

        Public Property BirthMonth() As Integer
            Get
                Return fpBirthMonth
            End Get
            Set(ByVal value As Integer)
                If value < 1 OrElse value > 12 Then value = 1
                fpBirthMonth = value
            End Set
        End Property

        Public Overrides Function ToString() As String
            'Return it anyway you like
            Return fpLastName & ", " & fpFirstName & "  Birth Month:" & fpBirthMonth.ToString
        End Function

        Public Shared Sub Insert(ByVal item As Person, ByVal fileName As String, ByVal append As Boolean)
            'This will add the person to the file passed in
            'Error checking required.

            Dim FileMode As IO.FileMode
            If append Then
                FileMode = IO.FileMode.Append
            Else
                FileMode = IO.FileMode.Create
            End If

            Dim FileStream As New IO.FileStream(fileName, FileMode)
            Dim BinaryWriter As New IO.BinaryWriter(FileStream)

            BinaryWriter.Write(Person.Serialize(item))

            BinaryWriter.Close()
            FileStream.Dispose()

        End Sub

        Public Shared Function SelectByMonth(ByVal birthMonth As Integer, ByVal fileName As String) As Person()
            'This will search the file passed in for each person that has the
            'same birth month.
            'It skips to the birth month byte index and checks it.
            'If matches it deserializes the person and adds it to
            'the list.
            'Match or no Match it skips to the next person without
            'reading any other fields.

            Dim FileStream As New IO.FileStream(fileName, IO.FileMode.Open)
            Dim BinaryReader As New IO.BinaryReader(FileStream)

            Dim LineLength As Integer
            Dim LineIndex As Integer
            Dim BirthIndex As Integer

            Dim FoundPeople As New List(Of Person)

            Do While BinaryReader.PeekChar <> -1

                LineLength = BinaryReader.ReadInt16
                'Skip the First name and last name indexes 
                'Int16 2 bytes each.
                FileStream.Position += 4 '+ firstname index and last index
                BirthIndex = BinaryReader.ReadInt16

                'Go directly to the birth month index.
                FileStream.Position = LineIndex + BirthIndex

                If CInt(BinaryReader.ReadInt16) = birthMonth Then
                    'Birth month matched.
                    'Back up to the start of the packet and deserialize it.
                    FileStream.Position = LineIndex
                    FoundPeople.Add(Person.Deserialze(BinaryReader.ReadBytes(LineLength)))
                End If

                'Set the postition of the stream to the next line
                'Set the Line index postion to the current line.
                FileStream.Position = LineLength + LineIndex
                LineIndex = FileStream.Position
            Loop

            FileStream.Dispose()
            BinaryReader.Close()

            Return FoundPeople.ToArray

        End Function

        Public Shared Function Deserialze(ByVal bytes As Byte()) As Person
            'Returns a new person on success or error.

            Dim It As New Person
            Dim MemoryStream As New IO.MemoryStream(bytes)
            Dim BinaryReader As New IO.BinaryReader(MemoryStream)

            Try
                'Skip the 8 byte packet header
                'Packet Length + FirstName Index + LastName Index + Birth Month Index
                'Int16 + Int16 + Int16 + Int16
                MemoryStream.Position = 8

                It.FirstName = BinaryReader.ReadString
                It.LastName = BinaryReader.ReadString
                It.BirthMonth = BinaryReader.ReadInt16

                MemoryStream.Dispose()
                BinaryReader.Close()

            Catch ex As Exception
            Finally
                MemoryStream.Dispose()
                BinaryReader.Close()
            End Try

            Return It

        End Function

        Public Shared Function Serialize(ByVal person As Person) As Byte()
            'this will serialize the person in bytes.
            '8 byte packet header
            '0 - 1 : Packet length
            '2 - 3 : Index of the first name
            '4 - 5 : Index of the Last Name
            '6 - 7 : Index of the birth month
            '8 +   : Person

            Dim MemoryStream As New IO.MemoryStream
            Dim BinaryWriter As New IO.BinaryWriter(MemoryStream)
            Dim HeaderSize As Integer = 8
            Dim Index As Integer
            Dim FirstNameIndex, LastNameIndex, MonthIndex As Integer

            'Make some room for the header
            MemoryStream.Position = HeaderSize

            'Now write the person to the stream and keep track
            'of where the byte index will be for each field.
            Index = HeaderSize

            FirstNameIndex = Index
            BinaryWriter.Write(person.FirstName)

            Index += MemoryStream.Position - Index

            LastNameIndex = Index
            BinaryWriter.Write(person.LastName)

            Index += MemoryStream.Position - Index

            MonthIndex = Index
            BinaryWriter.Write(Convert.ToInt16(person.BirthMonth))

            'Now write the packet header
            MemoryStream.Position = 0
            BinaryWriter.Write(Convert.ToInt16(MemoryStream.Length))
            BinaryWriter.Write(Convert.ToInt16(FirstNameIndex))
            BinaryWriter.Write(Convert.ToInt16(LastNameIndex))
            BinaryWriter.Write(Convert.ToInt16(MonthIndex))

            Return MemoryStream.ToArray

        End Function
    End Class

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        'Add a few people
        Dim It As Person
        For i = 0 To UBound(FirstNames)
            It = New Person
            It.FirstName = FirstNames(i)
            It.LastName = LastNames(i)
            It.BirthMonth = BirthMonths(i)
            Person.Insert(It, "C:\People.ppl", True)
        Next
      
        'When adding a class to a listbox it will display
        'its default ToString.
        'Sense the ToString is Overriden with what we want
        'thats what the listbox will display.
        ListBox1.Items.Clear()
        ListBox1.Items.AddRange(Person.SelectByMonth(2, "C:\People.ppl"))

    End Sub

End Class

Quick and dirty, huh? I would love to see what you do when you really mean business! :!) I really appreciate the help. I have to admit that some of what you have looks over my head at first blush. Some of the syntax is a bit different than what I am used to . I really can't wait until I can toss some stuff together. I have so much to learn!

I will look through this in some more detail and see what I can get out of it. Thank you again.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.