hey all,

i'm working on a code that i want to start creating new classes with but i want to know if there's a more direct way to send the variables used in the form to a new class for storage.

for example i've got this on a form...

Dim ClassID As String
        Dim ClassName As String
        Dim Grade As String
        Dim Exercise As String


        Dim file As String = "C:\Users\Ein05\Documents\Visual Studio 2008\Projects\GradeListApplication\GradeListApplication\Grades.txt"


        ClassID = xClassIDTextBox.Text
        ClassName = xStudentIDTextBox.Text
        Exercise = xExerciseTextBox.Text
        Grade = xGradeTextBox.Text


        My.Computer.FileSystem.WriteAllText(file, ControlChars.NewLine, True)


        My.Computer.FileSystem.WriteAllText(file, "Class ID: ", True)
        My.Computer.FileSystem.WriteAllText(file, ClassID, True)


        My.Computer.FileSystem.WriteAllText(file, ControlChars.NewLine, True)


        My.Computer.FileSystem.WriteAllText(file, " Class Name: ", True)
        My.Computer.FileSystem.WriteAllText(file, ClassName, True)


        My.Computer.FileSystem.WriteAllText(file, ControlChars.NewLine, True)


        My.Computer.FileSystem.WriteAllText(file, " Exercise: ", True)
        My.Computer.FileSystem.WriteAllText(file, Exercise, True)


        My.Computer.FileSystem.WriteAllText(file, ControlChars.NewLine, True)


        My.Computer.FileSystem.WriteAllText(file, " Grade: ", True)
        My.Computer.FileSystem.WriteAllText(file, Grade, True)


        My.Computer.FileSystem.WriteAllText(file, ControlChars.NewLine, True)
        My.Computer.FileSystem.WriteAllText(file, ControlChars.NewLine, True)


        xClassIDTextBox.Text = String.Empty
        xStudentIDTextBox.Text = String.Empty
        xExerciseTextBox.Text = String.Empty
        xGradeTextBox.Text = String.Empty

but now i want to create a class called Class (i know... creative right)

but i want to assign all of the variables as like properties and be able to sort of categorize them. so if the user enters more than 1 class the stored info will be like.

class 1: eng 101
class 2: eng 202

you know? so what would be my most direct route to get this?

and i want to UNDERSTAND so please critique me... but TEACH me as well. (for any snark comments out there)


thanx

Recommended Answers

All 4 Replies

You can do this as a class or even as a user defined structure (just discussed something similar here). However for this particular situation I would suggest creating a Typed Dataset with a DataTable inside that meets each of your fields. There are many benfits from adding it to a table such as giving you search, filter, displaying records, sending to reports and outputting the info to a file becomes simple to save, load and edit. Dataset.WriteXml("FileName") all done.

okay, sounds cool.

what i'm working with now is

<Serializable()> _
Public Class Course
    Implements System.ComponentModel.INotifyPropertyChanged

    Private mStringRep As String = String.Empty

    Public Event PropertyChanged(ByVal sender As Object, ByVal e As System.ComponentModel.PropertyChangedEventArgs) Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged

    Private mClassID As String = String.Empty

    Public Property mClassID() As String
        Get
            Return mClassID
        End Get

        Set(ByVal value As String)
            If Not mClassID = value Then
                mClassID = value
                OnPropertyChanged(New System.ComponentModel.PropertyChangedEventArgs("ClassID"))
            End If

        End Set
    End Property

    Private mExercise As String = String.Empty

    Public Property Exercise() As String
        Get
            Return mExercise
        End Get
        Set(ByVal value As String)
            If Not mExercise = value Then
                mExercise = value
                OnPropertyChanged(New System.ComponentModel.PropertyChangedEventArgs("Exercise"))
            End If
        End Set

    End Property

    Private mGrade As String = String.Empty

    Public Property Grade() As String
        Get
            Return mGrade
        End Get
        Set(ByVal value As String)
            If Not mGrade = value Then
                mGrade = value
                OnPropertyChanged(New System.ComponentModel.PropertyChangedEventArgs("Grade"))
            End If
        End Set
    End Property

    Private mStudentID As String = String.Empty

    Public Property StudentID() As String
        Get
            Return mStudentID
        End Get
        Set(ByVal value As String)
            If Not mStudentID = value Then
                mStudentID = value
                OnPropertyChanged(New System.ComponentModel.PropertyChangedEventArgs("StudentID"))
            End If
        End Set

    End Property

    Protected Overridable Sub OnPropertyChanged(ByVal e As System.ComponentModel.PropertyChangedEventArgs)
        GenerateStringRep()
        RaiseEvent PropertyChanged(Me, e)
    End Sub

    Private Sub GenerateStringRep()
        Dim sb As New System.Text.StringBuilder
        If mClassID.Length > 0 Then
            sb.AppendLine("Course Name: " & mClassID)
        End If
        If mStudentID.Length > 0 Then
            sb.AppendLine("Student ID: " & mStudentID)
        End If
        If mExercise.Length > 0 Then
            sb.AppendLine("Exercise: " & mExercise)
        End If
        If mGrade.Length > 0 Then
            sb.AppendLine("Grade: " & mGrade)
        End If
        mStringRep = sb.ToString
    End Sub

    Public Overrides Function ToString() As String
        Return mStringRep
    End Function

End Class

this

<Serializable()> _
Public Class CourseList

    Implements IList(Of Course)

    Private mInnerList As New List(Of Course)

    Public Shared Function FromSaveFile(ByVal pathToFile As String) As CourseList
        Dim fs As System.IO.FileStream = System.IO.File.Open(pathToFile, IO.FileMode.Open)
        Dim bf As New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
        Dim result As CourseList
        result = CType(bf.Deserialize(fs), CourseList)
        fs.Close()
        Return result
    End Function

    Protected Overridable Sub PerformSort()
        mInnerList.Sort(Function(c1 As Course, c2 As Course) c1.CourseNumber.CompareTo(c2.CourseNumber))
    End Sub

    Public Sub Add(ByVal item As Course) Implements System.Collections.Generic.ICollection(Of Course).Add
        mInnerList.Add(item)
        PerformSort()
    End Sub

    Public Sub Clear() Implements System.Collections.Generic.ICollection(Of Course).Clear
        mInnerList.Clear()
    End Sub

    Public Function Contains(ByVal item As Course) As Boolean Implements System.Collections.Generic.ICollection(Of Course).Contains
        Return mInnerList.Contains(item)
    End Function

    Public Sub CopyTo(ByVal array() As Course, ByVal arrayIndex As Integer) Implements System.Collections.Generic.ICollection(Of Course).CopyTo
        mInnerList.CopyTo(array, arrayIndex)
    End Sub

    Public ReadOnly Property Count() As Integer Implements System.Collections.Generic.ICollection(Of Course).Count
        Get
            Return mInnerList.Count
        End Get
    End Property

    Public ReadOnly Property IsReadOnly() As Boolean Implements System.Collections.Generic.ICollection(Of Course).IsReadOnly
        Get
            Return False
        End Get
    End Property

    Public Function Remove(ByVal item As Course) As Boolean Implements System.Collections.Generic.ICollection(Of Course).Remove
        Return mInnerList.Remove(item)
    End Function

    Public Function GetEnumerator() As System.Collections.Generic.IEnumerator(Of Course) Implements System.Collections.Generic.IEnumerable(Of Course).GetEnumerator
        Return mInnerList.GetEnumerator
    End Function

    Public Function IndexOf(ByVal item As Course) As Integer Implements System.Collections.Generic.IList(Of Course).IndexOf
        Return mInnerList.IndexOf(item)
    End Function

    Public Sub Insert(ByVal index As Integer, ByVal item As Course) Implements System.Collections.Generic.IList(Of Course).Insert
        Throw New NotSupportedException("Insert not supported on Auto-Sorted list")
    End Sub

    Default Public Property Item(ByVal index As Integer) As Course Implements System.Collections.Generic.IList(Of Course).Item
        Get
            Return mInnerList.Item(index)
        End Get
        Set(ByVal value As Course)
            If Not mInnerList.Item(index) Is value Then
                mInnerList.Item(index) = value
                PerformSort()
            End If
        End Set
    End Property

    Public Sub RemoveAt(ByVal index As Integer) Implements System.Collections.Generic.IList(Of Course).RemoveAt
        mInnerList.RemoveAt(index)
    End Sub

    Public Function GetEnumeratorBase() As System.Collections.IEnumerator Implements System.Collections.IEnumerable.GetEnumerator
        Return mInnerList.ToArray.GetEnumerator
    End Function

    Public Sub Save(ByVal pathToFile As String)
        Dim fs As System.IO.FileStream = System.IO.File.Create(pathToFile)
        Dim bf As New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
        bf.Serialize(fs, Me)
        fs.Close()
    End Sub

    Public Sub WriteToFile(ByVal pathToFile As String)
        Dim writer As System.IO.StreamWriter = System.IO.File.CreateText(pathToFile)
        For Each c As Course In mInnerList
            If writer.BaseStream.Position > 0 Then
                writer.WriteLine()
            End If
            writer.WriteLine(c.ToString)
        Next
        writer.Close()
    End Sub
End Class

& this which i picked up from a tutorial

'Create new example course list
Dim courses As New CourseList

Dim c1 As New Course
c1.CourseName = "Eng 101"
c1.CourseNumber = "1"
c1.Exercise = "Foo"
c1.Grade = "A"
c1.StudentID = "FFLINTSTONE"

courses.Add(c1)

Dim c2 As New Course
c2.CourseName = "Bio 101"
c2.CourseNumber = "2"
c2.Exercise = "Goo"
c2.Grade = "B"
c2.StudentID = "FFLINTSTONE"

courses.Add(c2)

'Write and display example text file
courses.WriteToFile("c:\test\testcourseoutput.txt")
System.Diagnostics.Process.Start("c:\test\testcourseoutput.txt")

'Save to binary file for later use
'make up your own extension; csf = course save file
courses.Save("c:\test\testsave.csf")

'Load save file into new courselist
Dim list2 As CourseList
list2 = CourseList.FromSaveFile("c:\test\testsave.csf")

'Example of adding another new course entry to the
'existing list loaded from the binary save file
Dim c3 As New Course
c3.CourseName = "Chem 101"
c3.CourseNumber = "3"
c3.Exercise = "Boo"
c3.Grade = "A"
c3.StudentID = "FFLINTSTONE"

list2.Add(c3)

'Write and display example text file
list2.WriteToFile("c:\test\testcourseoutput2.txt")
System.Diagnostics.Process.Start("c:\test\testcourseoutput2.txt")

but it isn't going how i want...

i want to take this original code

Public Class GForm1

    Private Sub xCancelButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles xCancelButton.Click
        Me.Close()
    End Sub

    Private Sub xSubmitButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles xSubmitButton.Click

        Dim ClassID As String
        Dim StudentID As String
        Dim Grade As String
        Dim Exercise As String

        Dim file As String = "C:\Users\Ein05\Documents\Visual Studio 2008\Projects\GradeListApplication\GradeListApplication\Grades.txt"

        ClassID = xClassIDTextBox.Text
        StudentID = xStudentIDTextBox.Text
        Exercise = xExerciseTextBox.Text
        Grade = xGradeTextBox.Text

        My.Computer.FileSystem.WriteAllText(file, ControlChars.NewLine, True)

        My.Computer.FileSystem.WriteAllText(file, "Class ID: ", True)
        My.Computer.FileSystem.WriteAllText(file, ClassID, True)

        My.Computer.FileSystem.WriteAllText(file, ControlChars.NewLine, True)

        My.Computer.FileSystem.WriteAllText(file, " Class Name: ", True)
        My.Computer.FileSystem.WriteAllText(file, StudentID, True)

        My.Computer.FileSystem.WriteAllText(file, ControlChars.NewLine, True)

        My.Computer.FileSystem.WriteAllText(file, " Exercise: ", True)
        My.Computer.FileSystem.WriteAllText(file, Exercise, True)

        My.Computer.FileSystem.WriteAllText(file, ControlChars.NewLine, True)

        My.Computer.FileSystem.WriteAllText(file, " Grade: ", True)
        My.Computer.FileSystem.WriteAllText(file, Grade, True)

        My.Computer.FileSystem.WriteAllText(file, ControlChars.NewLine, True)
        My.Computer.FileSystem.WriteAllText(file, ControlChars.NewLine, True)

        xClassIDTextBox.Text = String.Empty
        xStudentIDTextBox.Text = String.Empty
        xExerciseTextBox.Text = String.Empty
        xGradeTextBox.Text = String.Empty

        'final message to user before closing

        Dim button As DialogResult

        button = MessageBox.Show _
        ("Thank you for your submission, by clicking 'YES', your results will save and this window will close.  If you need to enter another record select 'NO', and you will be returned to your previous form to add another Grade Record.", _
        "Message", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1)

        If button = Windows.Forms.DialogResult.Yes Then
            MessageBox.Show("Thank You for your entry. Goodbye")
            Me.Close()
        End If

    End Sub
End Class

and then set up a new class that grabs the data fields collected on the Gform and use it as a Properties of the new class

but i think i will need a constructor to populate the members and after all that i want to output the info into a sequential access CSV file

Its a completly different direction but I would again suggest changing it to a DataTable instead of a class where your doing so much coding. Also there are just so many advantages as I pointed out above, specially when you want to do things such as work with many student records at a time.

'Creating a new record

Dim row as myTable.NewRow
row("ClassID ") = intNewId
row("StudentID")   = intStudentId
row("Grade") = strGrade
row("Exercise") = strExercise
myTable.Rows.Add(row)

'Displaying all records
DataGridView1.DataSource = myTable

Loading the records from a file is as simple as

myTable.LoadXml("MyFile")
'Saving
myTable.WriteXml("MyFile")

Sorting, Searching and filtering can be done by any column in the table

'Show all student records for a specified class id
myTable.DefaultView
myTable.Filter = "ClassId = " & intClassId

Updating a record

Dim row As DataRow
row = myTable.FindByStudentId(123)
row("Grade") = A+          'New grade

'Displaying and printing reports

Dim Report As MyReportName
Report.DataSource = myTable
report.PrintToPrinter(1, False, 0, 0)

Plus working with typed datasets give you automatic validation on datatypes, ability to set default values, limit string length etc

okay, just sent you a pm

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.