Page 1 of 2 12 LastLast
Results 1 to 40 of 44

Thread: Collections and updated Class properties

  1. #1

    Thread Starter
    Member
    Join Date
    Apr 2007
    Posts
    34

    Unhappy Collections and updated Class properties

    I have a CarCollection that inherits CollectionBase. I add the items in a Car Class to a combobox and to the Collection. I have a MakeCurrent button that makes the selectedindex in the combobox the current Car. When I run a method in the application that increases the Mileage (among other things) on the Current Car in the Collection the values(like MIleage) do not update. Only the last item in the combobox list will update.

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Collections and updated Class properties

    If you bind your collection to the ComboBox then that won't be an issue. Don't have two versions of the data: one for the ComboBox and one for the collection. Have one version of the data for the collection and then bind that to the control. The whole point of data-binding is that changes to the backing data are propagated to the control and vice versa.

    Create your CarCollection and bind it to a BindingSource, then bind the BindingSource to your ComboBox. Now to add a new Car to the collection you call the AddNew method of the BindingSource to update both the collection and the ComboBox. To get the selected Car you can use the ComboBox's SelectedItem property or the BindingSource's Current property. They will both return a reference to the same object, which you can then update. The object they refer to is in the bound collection, so it too is updated and everyone's happy.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  3. #3

    Thread Starter
    Member
    Join Date
    Apr 2007
    Posts
    34

    Unhappy Re: Collections and updated Class properties

    Thank you for your reply. I am not using a Data source. I believe that binding would apply in a situation where I was using a Data source. Am i right?

  4. #4
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Collections and updated Class properties

    Data-binding applies to any situation where you want to bind data to controls. You can bind all sorts of data. The DataSource property of a control accepts any object that implements the IList or IListSource interface. The most common data source are DataTables and BindingSources, but arrays and collections are just as valid. You assign your CarCollection object to the DataSource property of a BindingSource or control just as you can bind a DataTable.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  5. #5
    Junior Member
    Join Date
    Jul 2006
    Posts
    19

    Re: Collections and updated Class properties

    Jm, I tried what you suggested to trials_54 with an example of my own.

    After filling a collection 'Products' with objects 'Product',
    and adding this collection as the datasource to the bindingsource, then binding a combobox to the bindingsource, I get the following in my combobox

    [122,clsproducts.product]
    [123,clsproducts.product]
    [124,clsproducts.product]

    How do you set the displaymember and valuemember as properties of the 'Product'

    ps Did try combobox1.displaymember="ProductCode"

  6. #6
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Collections and updated Class properties

    Quote Originally Posted by Pickles89
    Jm, I tried what you suggested to trials_54 with an example of my own.

    After filling a collection 'Products' with objects 'Product',
    and adding this collection as the datasource to the bindingsource, then binding a combobox to the bindingsource, I get the following in my combobox

    [122,clsproducts.product]
    [123,clsproducts.product]
    [124,clsproducts.product]

    How do you set the displaymember and valuemember as properties of the 'Product'

    ps Did try combobox1.displaymember="ProductCode"
    If you have bound a collection of Product objects to a ComboBox and set the DisplayMember to "ProductCode" then your ComboBox will display a string representation of the ProductCode property of each item. Firstly, does the Product class have a ProductCode property? Check the spelling and note that the DisplayMember property is case-sensitive.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  7. #7
    Junior Member
    Join Date
    Jul 2006
    Posts
    19

    Re: Collections and updated Class properties

    Yes It does.

    Product Class
    Code:
      
    
        Private _ProductID As Integer
        Private _ProductCode As String
        Private _ProductDesc As String
    
     Public Property ProductID() As Integer
            Get
                Return _ProductID
            End Get
            Set(ByVal value As Integer)
                _ProductID = value
            End Set
        End Property
    
        Public Property ProductCode() As String
            Get
                Return _ProductCode
            End Get
            Set(ByVal value As String)
                _ProductCode = value
            End Set
        End Property
    
        Public Property ProductDescription() As String
            Get
                Return _ProductDesc
            End Get
            Set(ByVal value As String)
                _ProductDesc = value
            End Set
        End Property
    Testing
    Code:
        Private myB As New BindingSource
        Private myprods As New clsProducts.products
    
        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    
             myprods.GetProducts(13, False)  'Retrieves records via sql to fill a generic.dictionay collection
             myB.DataSource = myprods
    
            ComboBox1.DisplayMember = "ProductCode"
            ComboBox1.DataSource = myB
    Last edited by Pickles89; Apr 22nd, 2007 at 08:34 PM.

  8. #8
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Collections and updated Class properties

    That would suggest to me that that's what that property is returning.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  9. #9
    Junior Member
    Join Date
    Jul 2006
    Posts
    19

    Re: Collections and updated Class properties

    Was going to post a small full example. Then I twigged.

    myB.DataSource=myprods.VALUES

  10. #10

    Thread Starter
    Member
    Join Date
    Apr 2007
    Posts
    34

    Unhappy Re: Collections and updated Class properties

    Here is the binding I have done:
    txtVIN.Text = MyCarCollection.Item(cboCars.SelectedIndex).VIN.ToString
    txtMileage.Text = MyCarCollection.Item(cboCars.SelectedIndex).Mileage.ToString
    txtGasLevel.Text = MyCarCollection.Item(cboCars.SelectedIndex).GasLevel.ToString
    txtMaxGasLevel.Text = MyCarCollection.Item(cboCars.SelectedIndex).MaxGasLevel.ToString
    txtOilLevel.Text = MyCarCollection.Item(cboCars.SelectedIndex).Oil.ToString
    cboCars.Refresh()

  11. #11
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Collections and updated Class properties

    Quote Originally Posted by Pickles89
    Was going to post a small full example. Then I twigged.

    myB.DataSource=myprods.VALUES
    I take it then that your collection class is a custom Dictionary.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  12. #12

    Thread Starter
    Member
    Join Date
    Apr 2007
    Posts
    34

    Angry Re: Collections and updated Class properties

    Sorry. I don't know the term "custom dictionary". The CarCollection inherits CollectionBase.

  13. #13
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Collections and updated Class properties

    Quote Originally Posted by trials_54
    Here is the binding I have done:
    txtVIN.Text = MyCarCollection.Item(cboCars.SelectedIndex).VIN.ToString
    txtMileage.Text = MyCarCollection.Item(cboCars.SelectedIndex).Mileage.ToString
    txtGasLevel.Text = MyCarCollection.Item(cboCars.SelectedIndex).GasLevel.ToString
    txtMaxGasLevel.Text = MyCarCollection.Item(cboCars.SelectedIndex).MaxGasLevel.ToString
    txtOilLevel.Text = MyCarCollection.Item(cboCars.SelectedIndex).Oil.ToString
    cboCars.Refresh()
    That's not binding. That's just assigning a bunch of values to your TextBoxes. If it was binding you wouldn't have to do any of that. First you should bind your CarCollection to the ComboBox, e.g.
    vb Code:
    1. cboCars.DisplayMember = "Name"
    2. cboCars.ValueMember = "ID"
    3. cboDataSource = myCarCollection
    Now you bind the other properties to the TextBoxes, e.g.
    vb Code:
    1. txtVIN.DataBindings.Add("Text", myCarCollection, "VIN")
    2. txtMileage.DataBindings.Add("Text", myCarCollection, "Mileage")
    and so on for each TextBox. Now when you select a car in the ComboBox all TextBoxes will update automatically. Also, if you edit a value in a TextBox the corresponding item in the collection will be updated automatically. That's what data-binding means: the UI and backing data store are bound so a change to one also affects the other.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  14. #14

    Thread Starter
    Member
    Join Date
    Apr 2007
    Posts
    34

    Unhappy Re: Collections and updated Class properties

    i'm sorry but I don't know what "Display Member" and "Value Member" refer to.

  15. #15

    Thread Starter
    Member
    Join Date
    Apr 2007
    Posts
    34

    Angry Re: Collections and updated Class properties

    I believe that your method is way more efficient however this project is for a Class in OOP in am taking and we haven't covered Data Bindings yet and I think I should stick to using what I know.

  16. #16
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Collections and updated Class properties

    Quote Originally Posted by trials_54
    I believe that your method is way more efficient however this project is for a Class in OOP in am taking and we haven't covered Data Bindings yet and I think I should stick to using what I know.
    Okeydokey then. In that case then you should get the selected car only once:
    vb Code:
    1. Dim selectedCar As Car = myCarCollection(cboCars.SelectedIndex)
    Now you can get or set the properties of 'selectedCar'.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  17. #17

    Thread Starter
    Member
    Join Date
    Apr 2007
    Posts
    34

    Unhappy Re: Collections and updated Class properties

    I don't see how this will get the values of VIN and Mileage, etc. into the textboxes.

  18. #18
    PowerPoster VBDT's Avatar
    Join Date
    Sep 2005
    Location
    CA - USA
    Posts
    2,922

    Re: Collections and updated Class properties

    how do you change the values of the car. Show the method.

  19. #19

    Thread Starter
    Member
    Join Date
    Apr 2007
    Posts
    34

    Angry Re: Collections and updated Class properties

    just the constuctor in the Car Class

  20. #20
    PowerPoster VBDT's Avatar
    Join Date
    Sep 2005
    Location
    CA - USA
    Posts
    2,922

    Re: Collections and updated Class properties

    Quote Originally Posted by trials_54
    just the constuctor in the Car Class
    Ok, now I am confused. What is the problem you are having? In your first post the problem was that even though you assigned new values to the car properties, they didn’t change. That means that the object is already created so how you change the properties in the constructor?

  21. #21

    Thread Starter
    Member
    Join Date
    Apr 2007
    Posts
    34

    Unhappy Re: Collections and updated Class properties

    Well, the Drive method takes the current values for Mileage and GasLevel from the Car that is selected and changes the values by adding miles and reducing gas consumption.

  22. #22
    PowerPoster VBDT's Avatar
    Join Date
    Sep 2005
    Location
    CA - USA
    Posts
    2,922

    Re: Collections and updated Class properties

    Ok show the Drive method!!!

  23. #23
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Collections and updated Class properties

    Let's look at the VIN property only for the moment. Your car class should look something like this:
    vb Code:
    1. Public Class Car
    2.  
    3.     Private _vin As String
    4.  
    5.     Public Property Vin() As String
    6.         Get
    7.             Return Me._vin
    8.         End Get
    9.         Set(ByVal value As String)
    10.             Me._vin = value
    11.         End Set
    12.     End Property
    13.  
    14. End Class
    You would create a Car object something like this:
    vb Code:
    1. Dim myCar As New Car
    2.  
    3. myCar.Vin = "ABC123"
    If you want to declare a constructor that takes property values you can:
    vb Code:
    1. Public Sub New(ByVal vin As String)
    2.     Me._vin = vin
    3. End Sub
    In that case you could create a Car object like this:
    vb Code:
    1. Dim myCar As New Car("ABC123")
    Now in your application, if you want to forgo data binding then you can add the contents of a CarCollection to a ComboBox:
    vb Code:
    1. For Each myCar As Car In myCarCollection
    2.     Me.ComboBox1.Items.Add(myCar.ToString)
    3. Next myCar
    You'd have to change the ToString part to the name of the property you wanted to display. Now you would handle all the property chnages like so:
    vb Code:
    1. Private myCarCollection As New CarCollection
    2. Private selectedCar As Car
    3.  
    4. Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, _
    5.                                            ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
    6.     If Me.ComboBox1.SelectedIndex = -1 Then
    7.         Me.selectedCar = Nothing
    8.         Me.TextBox1.Clear()
    9.     Else
    10.         Me.selectedCar = Me.myCarCollection(Me.ComboBox1.SelectedIndex)
    11.         Me.TextBox1.Text = Me.selectedCar.Vin
    12.     End If
    13. End Sub
    14.  
    15. Private Sub TextBox1_Validated(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.Validated
    16.     If Not Me.selectedCar Is Nothing Then
    17.         Me.selectedCar.Vin = Me.TextBox1.Text
    18.     End If
    19. End Sub
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  24. #24

    Thread Starter
    Member
    Join Date
    Apr 2007
    Posts
    34

    Unhappy Re: Collections and updated Class properties

    Thanks. I already have everything you wrote(almost exactly) except the last part with the SelectedIndexChanged and Validating. When I add code like yours to Validating it tells me the VIN is read only (which it how I coded it and the only way into it is the Sub New Constructor.

  25. #25
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Collections and updated Class properties

    Well if you don't want to change the VIN then don't try to set the VIN property. Just apply the principle to the properties that you DO want to change. You should set the ReadOnly property of any TextBoxes that will contain the values of ReadOnly properties.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  26. #26

    Thread Starter
    Member
    Join Date
    Apr 2007
    Posts
    34

    Unhappy Re: Collections and updated Class properties

    I am suppose to use a MakeCurrent button to select the VIN from the ComboBox which will make the Car associated with that VIN current and I am not too familiar with SelectedIndexChanged. So I added the code you suggested for SelectedIndexChanged to my MakeCurrent button and the program behaves exactly as before. When I make the last Car and VIN added(to the Collection and the ComboBox) and run the Drive method the new values pop up in the text boxes as they should. But when I select any other VIN in the list the values are never changed.

  27. #27
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Collections and updated Class properties

    How are you populating the ComboBox in the first place?
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  28. #28

    Thread Starter
    Member
    Join Date
    Apr 2007
    Posts
    34

    Unhappy Re: Collections and updated Class properties

    Private Sub collect_car_VIN() 'sub procedure to add VINs to ComboBox


    If counter >= 0 Then

    cboCars.Items.Add(MyCarCollection.Item(counter).VIN)
    counter += 1

    End If

    End Sub

  29. #29
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Collections and updated Class properties

    So when you do this:
    vb Code:
    1. Me.selectedCar = Me.myCarCollection(Me.ComboBox1.SelectedIndex)
    are you then getting the properties of the 'selectedCar' variable? If so I don't see how you could be getting the wrong values. If you test the VIN property of the 'selectedCar' does it give you the value displayed in the ComboBox?

    Actually, just show us the code you're using to get the properties of the Car. You should have done that in the beginning so we didn't have to draw this out inch by inch. If you're having trouble with some code then show the code.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  30. #30

    Thread Starter
    Member
    Join Date
    Apr 2007
    Posts
    34

    Unhappy Re: Collections and updated Class properties

    I am getting the right values initially. I can switch between the VINs in the Combo box and all the textboxes fill with the right values. But when I run the Drive method only the last VIN added will give me back the right adjusted values.

  31. #31
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Collections and updated Class properties

    Then you're calling the Drive method of the wrong Car object. The 'selectedCar' variable refers to the Car that has been selected. THAT is the Car whose Drive method you should be calling, i.e. the same Car object whose properties you displayed in the TextBoxes. That's what the 'selectedCar' variable is for: to refer to the selected car.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  32. #32

    Thread Starter
    Member
    Join Date
    Apr 2007
    Posts
    34

    Unhappy Re: Collections and updated Class properties

    It is performing the Drive method on the wrong car. I know that. But the values in the textboxes when I run Drive reflex the Car I picked from the ComboBox. But its still running it on the wrong car. After the Drive method is run the values don't change but they should .Running the Drive method when the last Car added is selected works.

  33. #33
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Collections and updated Class properties

    Show Us The Code.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  34. #34

    Thread Starter
    Member
    Join Date
    Apr 2007
    Posts
    34

    Unhappy Re: Collections and updated Class properties

    Sorry. I guess i don't know how to post code here in the messagbox properly.

  35. #35

    Thread Starter
    Member
    Join Date
    Apr 2007
    Posts
    34

    Re: Collections and updated Class properties

    Did anyone look at my code?

  36. #36

    Thread Starter
    Member
    Join Date
    Apr 2007
    Posts
    34

    Unhappy Re: Collections and updated Class properties

    I see that my code didn't post. I will try again
    Here is the Car Class:Public Class Car
    Public Event OilGood() 'declare events
    Public Event ClearMiles()
    Public Event LowOil()
    Public Event ClearTextbox1()
    Public Event GasLow()
    Public Event RemoveCar()
    Public Event RefreshCurrent()


    Protected blnServLight As Boolean
    Protected sVIN As String 'private instance variables
    Protected sOil As Single
    Protected intMileage As Integer 'protected instance variables
    'so derived class has access
    Protected sngGasLevel As Single
    Private sngMaxGasLevel As Single


    Public ReadOnly Property VIN() As String 'VIN property procedure
    'read only

    Get 'accessor that is invoked when
    'a request to retrieve the property value is made
    Return Me.sVIN

    End Get
    End Property
    Public ReadOnly Property Mileage() As Integer 'Mileage property procedure
    Get
    Return Me.intMileage

    End Get
    End Property
    Public Property GasLevel() As Single 'GasLevel property procedure
    Get

    Return Me.sngGasLevel 'return value like a function

    End Get
    Set(ByVal Value As Single)
    Me.sngGasLevel = Value

    If Value < 0 Then 'check for proper value
    MessageBox.Show("Please enter a positive value for Gas Level!" _
    & ControlChars.CrLf & "Gas level is below '0'", "Negative Gas Level!", _
    MessageBoxButtons.OK, MessageBoxIcon.Exclamation)


    RaiseEvent ClearTextbox1() 'event raised

    ElseIf Value >= 0 And Value < 2 Then 'conditional clause

    RaiseEvent GasLow() 'event raised

    ' Me.sngGasLevel = Value

    ElseIf Value > Me.MaxGasLevel Then

    MessageBox.Show("Tank is overfilled! Exceeded Max" & _
    " " & "gas level!", "Too much gas!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)

    RaiseEvent ClearTextbox1() 'event raised

    Else

    Me.sngGasLevel = Value 'assings Value parameter to
    'private instance variable
    End If

    End Set
    End Property
    Public Property MaxGasLevel() As Single 'MaxGasLevel property procedure
    Get

    Return Me.sngMaxGasLevel

    End Get
    Set(ByVal Value As Single)

    Me.sngMaxGasLevel = Value

    End Set
    End Property

    Public ReadOnly Property Oil() As Single
    'read only property procedure
    Get
    Return Me.sOil

    End Get
    End Property
    Public Overridable ReadOnly Property ServiceLight() As Boolean
    Get 'property procedure
    Return blnServLight

    End Get
    End Property
    Sub New(ByVal VIN_Num As String, ByVal Mileage_Go As Integer, _
    ByVal service As Boolean, ByRef count As Integer)

    'Constructor

    Me.sVIN = VIN_Num 'assign parameters passed to Get of Property
    'procedures
    Me.intMileage = Mileage_Go

    End Sub
    Public Overridable Function Drive(ByVal decMiles As Decimal) As Boolean
    'Drive Class Method
    'Overriable

    If decMiles >= 0 Then
    MessageBox.Show("The current mileage on the car has been increased " & _
    ControlChars.CrLf & "by the amount you entered in the textbox and " & _
    ControlChars.CrLf & "the gas level has been decrease by 10% of the " & _
    ControlChars.CrLf & "total mileage. To see these changes reflected please " & _
    ControlChars.CrLf & " click on the Display button.")

    Me.intMileage += CInt(decMiles)

    Me.GasLevel -= CSng((0.1 * Mileage))
    RaiseEvent RefreshCurrent()

    Else
    Dim bCheck As Boolean
    bCheck = True

    Throw New NegativeAmountDrivenException(decMiles, bCheck)

    End If

    End Function
    Public Overridable Sub PumpGas(ByVal sngNumGal As Single) 'Class Method
    If Me.GasLevel < 0 Then 'checks for proper value entered

    MessageBox.Show("You need to add gas ", "No Gas in tank! ", _
    MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
    ElseIf Me.GasLevel > Me.MaxGasLevel Then
    MessageBox.Show("Too much gas in tank!", "Overmax!", MessageBoxButtons.OK, _
    MessageBoxIcon.Exclamation)
    Else
    If sngNumGal >= 0 Then
    Me.GasLevel += sngNumGal 'computation using parameter passed
    Else
    Throw New AmountPumpedNegativeException(sngNumGal)
    End If

    End If

    End Sub

    Public Overridable Sub DisplayPropValues(ByVal ReceiveTxt As String, _
    ByVal counter As Integer, ByVal ReceiveMile As String, _
    ByVal MakeCurrentRun As Boolean, ByVal ReceivedGasLev As String, _
    ByVal ReceiveMaxGas As String, ByVal ReceiveOil As String)

    'Class method overridable
    Dim bValue As Boolean
    ' Dim counter As Integer
    If Not MakeCurrentRun Then

    If MessageBox.Show("VIN number is: " & Me.VIN & _
    ControlChars.CrLf & "Mileage is: " & Me.Mileage _
    & " Miles" & ControlChars.CrLf & "Gas Level is: " & _
    FormatNumber(Me.GasLevel) & " Gallons" & ControlChars.CrLf & _
    "Max Gas Level is: " & FormatNumber(Me.MaxGasLevel) & " Gallons" & ControlChars.CrLf & _
    "Oil level is: " & Me.sOil & " Quarts" & ControlChars.CrLf & _
    "Do you want to create a new Car?", "New Car?", MessageBoxButtons.YesNo, _
    MessageBoxIcon.Question) = DialogResult.Yes Then


    Dim mycar As Car 'new instance of Car Class
    mycar = New Car(sVIN, intMileage, bValue, counter)


    RaiseEvent ClearTextbox1() 'event raised
    Else
    RaiseEvent ClearMiles()

    End If
    Else
    If MessageBox.Show("VIN number is: " & ReceiveTxt & _
    ControlChars.CrLf & "Mileage is: " & ReceiveMile _
    & " Miles" & ControlChars.CrLf & "Gas Level is: " & _
    ReceivedGasLev & " Gallons" & ControlChars.CrLf & _
    "Max Gas Level is: " & ReceiveMaxGas & " Gallons" & ControlChars.CrLf & _
    "Oil level is: " & Me.sOil & " Quarts" & ControlChars.CrLf & _
    "Do you want to create a new Car?", "New Car?", MessageBoxButtons.YesNo, _
    MessageBoxIcon.Question) = DialogResult.Yes Then

    Dim mycar As Car 'new instance of Car Class
    mycar = New Car(sVIN, intMileage, bValue, counter)

    RaiseEvent ClearTextbox1() 'event raised
    Else
    RaiseEvent ClearMiles()

    End If

    End If
    End Sub

    Public Sub Check_Oil(ByVal sngOilLev As Single) 'Class method


    sOil = sngOilLev 'parameter assigned to private instance
    'variable
    If Me.sOil <= 2 Then

    RaiseEvent LowOil() 'event raised
    Else
    RaiseEvent OilGood() 'event raised

    End If
    End Sub

    Public Sub Add_Oil(ByVal sngOil As Single) 'Class method to
    'assign parameter to read only property using private instance
    'variable

    sOil = sngOil

    End Sub
    Public Overridable Sub Unique_VIN(ByVal vin_unique() As String, _
    ByVal vin As String, ByVal intcount As Integer, ByVal intcount2 As Integer) 'ByRef vin_unique() As String, _
    'overridable sub that tests for duplicate VINs (will not work for Old Car
    'VIN duplicate check.. just serves so MyBetterCar overrided method works)

    If intcount2 > 1 Then 'tests for number of times Click Event
    'that creates Better Car has been run

    Do While intcount > 0 'do.. while loop to test for
    'duplicate VINs

    intcount -= 1

    If vin_unique(intcount) = vin Then

    intcount -= 1

    Throw New NonUniqueVINException(vin) 'exception throw

    End If
    Loop
    End If
    End Sub

    End Class

  37. #37

    Thread Starter
    Member
    Join Date
    Apr 2007
    Posts
    34

    Unhappy Re: Collections and updated Class properties

    Here is the BetterCar Class:
    Imports System.Text.RegularExpressions 'imports class


    Public Class BetterCar
    Inherits Car 'inherits Base class Car

    Dim NewValidate As Validate 'delclare Validate class
    ' protected blnServLight As Boolean 'private instance variable
    Public Event NeedService() 'declare events
    Public Event ClearTextbox()
    Public Event ClearMiles1()
    Public Event RefreshCurrent2()



    Const intBase As Integer = 5000 'constant variables
    Const intBaseUp As Integer = 10000


    Public Overrides ReadOnly Property ServiceLight() As Boolean


    Get 'property procedure
    Return blnServLight

    End Get
    End Property
    Public Overrides Function Drive(ByVal decMiles As Decimal) As Boolean

    'Drive method from Car Class
    'overidden
    Dim strFirst As String
    If decMiles >= 0 Then

    MessageBox.Show("The current mileage on the car has been increased by: " & _
    FormatNumber(decMiles, 0) & " Miles." & ControlChars.CrLf & _
    "The gas level has been decrease by 1% of the total mileage." _
    & ControlChars.CrLf & "To see these changes reflected please " & _
    " " & "click on the Display button.")


    MyBase.intMileage += CInt(decMiles)

    MyBase.GasLevel -= CSng((0.01 * MyBase.Mileage))

    RaiseEvent RefreshCurrent2()


    strFirst = MyBase.intMileage.ToString.Chars(0)

    If MyBase.intMileage = intBase Then
    RaiseEvent NeedService()

    ElseIf MyBase.intMileage = intBase + (intBaseUp * CDbl(strFirst)) Then
    'determine if mileage is in increments of 10k after 5k
    RaiseEvent NeedService() 'raises event

    Else

    Me.Light_Off() 'calls procedure
    Return True
    End If


    Else
    Throw New NegativeAmountDrivenException(decMiles, True) 'throws exception

    End If

    End Function

    Public Sub New(ByVal vin_num As String, ByVal mileage_go As Integer _
    , ByVal service As Boolean, ByRef count As Integer) 'construtor

    MyBase.New(vin_num, mileage_go, True, count) 'reference to Base Class
    'sub new

    End Sub


    Public Sub Light() 'Class method
    blnServLight = True
    RaiseEvent NeedService() 'raises event

    End Sub
    Public Sub Light_Off() 'Class method
    blnServLight = False
    MessageBox.Show("You do not need a schedualed service at this time." & _
    ControlChars.CrLf & "You should now see the service light is off")

    End Sub
    Public Sub Light_On() 'Class method

    blnServLight = True

    MessageBox.Show("You should now see the service light is on.", _
    "Attention!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)

    End Sub
    Public Overrides Sub DisplayPropValues(ByVal ReceiveTxt As String, _
    ByVal counter As Integer, ByVal ReceiveMile As String, _
    ByVal makecurrentrun As Boolean, ByVal receivedGasLev As String, _
    ByVal receiveMaxGas As String, ByVal receiveOil As String)


    'Car Class method
    'overriden
    NewValidate = New Validate
    Dim bValue As Boolean
    ' Dim counter As Integer
    If Not makecurrentrun Then

    If MessageBox.Show("VIN number is: " & Me.VIN & _
    ControlChars.CrLf & "Mileage is: " & Me.Mileage _
    & " Miles" & ControlChars.CrLf & "Gas Level is: " & _
    FormatNumber(Me.GasLevel) & " Gallons" & ControlChars.CrLf & _
    "Max Gas Level is: " & FormatNumber(Me.MaxGasLevel) & " Gallons" & ControlChars.CrLf & _
    "Oil level is: " & Me.sOil & " Quarts" & ControlChars.CrLf & _
    "Do you want to create a new Car?", "New Car?", MessageBoxButtons.YesNo, _
    MessageBoxIcon.Question) = DialogResult.Yes Then



    Dim MyBetterCar As BetterCar 'new instance of BetterCar Class
    MyBetterCar = New BetterCar(sVIN, intMileage, bValue, counter)


    RaiseEvent ClearTextbox() 'event raised

    Else
    RaiseEvent ClearMiles1()
    End If

    Else
    If MessageBox.Show("VIN number is: " & ReceiveTxt & _
    ControlChars.CrLf & "Mileage is: " & ReceiveMile _
    & " Miles" & ControlChars.CrLf & "Gas Level is: " & _
    receivedGasLev & " Gallons" & ControlChars.CrLf & _
    "Max Gas Level is: " & receiveMaxGas & " Gallons" & ControlChars.CrLf & _
    "Oil level is: " & receiveOil & " Quarts" & ControlChars.CrLf & _
    "Do you want to create a new Car?", "New Car?", MessageBoxButtons.YesNo, _
    MessageBoxIcon.Question) = DialogResult.Yes Then

    Dim mycar As Car 'new instance of Car Class
    mycar = New Car(sVIN, intMileage, bValue, counter)

    RaiseEvent ClearTextbox() 'event raised
    Else

    RaiseEvent ClearMiles1()

    End If

    End If

    End Sub
    Public Overrides Sub PumpGas(ByVal sngNumGal As Single)
    If Me.GasLevel < 0 Then 'checks for proper value entered

    MessageBox.Show("You need to add gas ", "No Gas in tank! ", _
    MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
    ElseIf Me.GasLevel > Me.MaxGasLevel Then
    MessageBox.Show("Too much gas in tank!", "Overmax!", MessageBoxButtons.OK, _
    MessageBoxIcon.Exclamation)
    Else
    If sngNumGal >= 0 Then
    Me.GasLevel += sngNumGal 'computation using parameter passed
    Else
    Throw New AmountPumpedNegativeException(sngNumGal) 'throws exception
    End If

    End If
    End Sub
    Public Overrides Sub Unique_VIN(ByVal vin_unique() As String, _
    ByVal vin As String, ByVal intcount As Integer, ByVal intcount2 As Integer)

    If intcount2 > 1 Then 'tests for number of times Click Event
    'that creates Better Car has been run

    Do While intcount > 0 'do.. while loop to test for
    'duplicate VINs

    intcount -= 1

    If vin_unique(intcount) = vin Then

    intcount -= 1

    Throw New NonUniqueVINException(vin) 'exception throw

    End If
    Loop
    End If

    End Sub


    End Class

  38. #38

    Thread Starter
    Member
    Join Date
    Apr 2007
    Posts
    34

    Unhappy Re: Collections and updated Class properties

    Here is the first part of the Form Class Inherits System.Windows.Forms.Form
    Dim WithEvents NewValidate As Validate 'declares NewValidate
    'object as Validate type

    Public Event ClearTextbox1() 'event declaration
    'declare variable to hold first VIN
    Dim strVINunique() As String
    Dim intCount As Integer = 0 'index of array
    Dim intCount2 As Integer = 0
    'declares counter that increments
    'everytime the form in opened
    Dim counter As Integer = 0
    Dim WithEvents MyCar As Car 'declares MyCar object
    Dim WithEvents MyBetterCar As BetterCar 'declares MyBetterCar object
    Dim WithEvents MyCarCollection As CarCollection
    Public SendTxt As String
    Public SendMile As String
    Public MakeCurrentRun As Boolean
    Public SendGasLev As String
    Public SendMaxGas As String
    Public SendOil As String
    Private selectedCar As Car'This program uses the BetterCar Class object which is a derived Class
    'of the Car Class to use the Property Values and Methods of the Base
    'Class again in the Derived Class. Overrides Drive method of the Car
    'Class to change the percentage of Gas used corresponding to Mileage
    'It also has some user defined Exception Classes that handle runtime
    'errors not handled by the System Exceptions.Program adds new Cars and
    'BetterCars to Collection. Collection class inherits CollectionBase.VINs
    'are added to ComboBox. MakeCurrent button on form selects VIN form list in
    'ComboBox and brings up property valules for the Car associated with VIN.
    'Delete Car button availabel. Checks for duplicate VINs

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCreateBetterCar.Click
    NewValidate = New Validate 'declare instance of Class object
    ' Dim intCount As Integer

    Dim strVIN As String 'declare variable for VIN
    strVIN = txtVIN.Text'assign textbox text property to
    'VIN variable

    intCount += 1 'index for array incremented
    intCount2 += 1 'count for button click event
    'incremented

    'validity check
    If NewValidate.ValidateData(txtMileage, "Mileage") Then

    If NewValidate.ValidateData(txtGasLevel, "Gas Level") Then

    If NewValidate.ValidateData(txtMaxGasLevel, "Max Gas Level") Then
    If NewValidate.ValidateData(txtOilLevel, "Oil Level") Then

    End If
    End If
    End If
    End If

    Dim bValue As Boolean
    'variable declarations
    Dim intMileage As Integer
    Dim sngOil_Lev As Single

    Try

    Try 'try... catch to
    'catch invalid cast exception and display messagebox

    ' Form1.ActiveForm.ResetText()

    intMileage = CInt(txtMileage.Text)


    sngOil_Lev = CSng(txtOilLevel.Text)
    bValue = False 'set value of boolean variable

    'declare
    'instance of the BetterCar Class with parameters
    Try
    MyBetterCar = New BetterCar(strVIN, intMileage, bValue, counter)

    ReDim Preserve strVINunique(intCount) 'redimension
    'array so there is no limit on how many values it can
    'hold; also preserve values already held

    strVINunique(intCount) = strVIN 'assign VIN variable
    'to array


    Finally 'execute the following statements
    'no matter whether exception is throw or not
    MyBetterCar.Add_Oil(sngOil_Lev)


    MyBetterCar.MaxGasLevel = CSng(txtMaxGasLevel.Text) 'assign
    'textbox text property to Class property
    MyBetterCar.GasLevel() = CSng(txtGasLevel.Text)

    End Try


    Catch esystem As NullReferenceException 'catch system exception and
    'display message to user
    MessageBox.Show("We are unable to create your New Car due to the " & _
    "problem with the VIN number you entered. Sorry.")

    End Try

    Catch eSystem As InvalidCastException 'catch if user enters
    'wrong types of values in textboxes
    MessageBox.Show("You must enter a numeric value above zero" _
    & ControlChars.CrLf & " in all fields.")

    End Try
    Try
    If (MyCarCollection Is Nothing) Then
    Try ' 'try.. catch

    ' MyBetterCar.Unique_VIN(strVINunique, strVIN, intCount, intCount2)
    'call to Inherited Class to test for duplicate VINs

    MyCarCollection = New CarCollection

    Catch esystem As NullReferenceException 'catch system exception
    MessageBox.Show("Car does not exist!")

    End Try

    End If

    Dim message As String = ""

    MyCarCollection.Add(MyBetterCar, intCount, intCount2, strVIN, message) 'add MyBetterCar object to Collection
    If intCount <= 10 Then
    MessageBox.Show("This is the " & message & " car you have added.")
    End If


    Me.collect_car_VIN()
    Catch err As InvalidVINexception 'catch user defined exception
    MessageBox.Show(err.Message) 'show error message stored in
    'constuctor()
    Catch err As InvalidVINPatternException 'catch user defined
    'exception
    MessageBox.Show(err.Message)
    ' Catch err As NonUniqueVINException 'catch user defined exception
    Me.ClearText()

    Catch err As NonUniqueVINException 'catch user defined
    'exception
    MessageBox.Show(err.Message) 'show error message
    Me.ClearText()

    Catch esystem As NullReferenceException 'catch system exception
    MessageBox.Show("Please enter a VIN number that conforms to all of the " & _
    ControlChars.CrLf & "requirements. Thank you.")

    End Try

    End Sub
    Public Sub myBetterCar_NeedService() Handles MyBetterCar.NeedService
    'event handler for NeedService event
    Dim result As DialogResult

    If MessageBox.Show("You are now at: " & FormatNumber(MyBetterCar.Mileage, 0) & _
    " Miles" & ControlChars.CrLf & "Please service your car! You already did?" _
    & ControlChars.CrLf & "Then click 'Yes' .If you haven't yet, please answer 'No'.", _
    " Need Service!", MessageBoxButtons.YesNo, MessageBoxIcon.Question) _
    = Windows.Forms.DialogResult.Yes Then
    Me.ServLightOff()

    MyBetterCar.Light_Off()

    ElseIf result = Windows.Forms.DialogResult.No Then

    Me.ServLightOn()

    MyBetterCar.Light_On()

    End If

    End Sub

    Private Sub btnDrive_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDrive.Click
    Dim intMiles As Integer

    Try 'try.. catch
    intMiles = CInt(txtMiles.Text)

    Try
    If MyBetterCar.Drive(intMiles) = True Then
    'call to Class method which
    'is overridden
    Me.ServLightOff()

    End If

    Catch err As NegativeAmountDrivenException 'catch user defined
    'exception
    MessageBox.Show(err.Message & "The source of the problem is: " & _
    err.Source)
    Dim bCheck As Boolean = True

    If bCheck = True Then Me.ClearText()

    End Try

    Catch ex As InvalidCastException 'catch system exception

    MessageBox.Show("You must enter values into all the textboxes and " & _
    ControlChars.CrLf & "click the 'Create' button before using this control")

    End Try

    End Sub

  39. #39
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Collections and updated Class properties

    That's far too much code. Post the relevant code only, and inside VBCODE tags. Post the part where you get the properties of the selected car, call its Drive method and then set its properties.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  40. #40

    Thread Starter
    Member
    Join Date
    Apr 2007
    Posts
    34

    Re: Collections and updated Class properties

    Form Class cont.Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click

    If MessageBox.Show("Are you sure you want to exit?", "Exit?", _
    MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
    MyCar = Nothing 'manually clear garbage
    MyBetterCar = Nothing

    Me.Close() 'closes program at user request
    Else
    Me.Focus() 'call to procedure
    txtVIN.Focus()
    End If

    End Sub

    Private Sub btnOldDrive_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOldDrive.Click
    Dim intMiles As Integer

    Try
    intMiles = CInt(txtMiles.Text)
    MyCar.Drive(intMiles) 'call to Base Class method

    Catch err As NegativeAmountDrivenException
    MessageBox.Show(err.Message & "The source of the problem is: " & _
    err.Source)

    Dim bCheck As Boolean = True


    If bCheck = True Then Me.ClearText()

    Catch ex As InvalidCastException 'catch system exception

    MessageBox.Show("You must enter values into all the textboxes and " & _
    ControlChars.CrLf & "click the 'Create' button before using this control")

    End Try

    End Sub
    Public Sub ClearText() 'sub procedure to clear textboxes
    Dim ctlcontrol As Control
    For Each ctlcontrol In Me.Controls

    If TypeOf ctlcontrol Is TextBox Then
    With ctlcontrol

    .Text = ""
    .Focus()
    End With
    End If

    Next

    End Sub

    Private Sub btnClearText_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClearText.Click
    Me.ClearText()

    End Sub
    Public Sub MyBetterCar_ClearTextboxes() Handles MyBetterCar.ClearTextbox
    Dim ctlcontrol As Control 'Event handler
    For Each ctlcontrol In Me.Controls

    If TypeOf ctlcontrol Is TextBox Then
    With ctlcontrol

    .Text = ""
    .Focus()
    End With
    End If

    Next
    End Sub
    Public Sub MyCar_ClearTextboxes() Handles MyCar.ClearTextbox1
    Dim ctlcontrol As Control 'Event handler
    For Each ctlcontrol In Me.Controls

    If TypeOf ctlcontrol Is TextBox Then
    With ctlcontrol

    .Text = ""
    .Focus()
    End With
    End If

    Next
    End Sub
    Private Sub MyCar_ClearMiles() Handles MyCar.ClearMiles
    'event handler
    Me.txtMiles.Clear()

    End Sub
    Private Sub MyBetterCar_ClearMiles1() Handles MyBetterCar.ClearMiles1
    'event handler
    Me.txtMiles.Clear()

    End Sub

    Private Sub btnDisplay_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDisplayBetter.Click
    ' Dim sendtxt As String

    Try

    MyBetterCar.DisplayPropValues(SendTxt, counter, SendMile, _
    MakeCurrentRun, SendGasLev, SendMaxGas, SendOil)

    'call to Derived Class method(overidden)


    Catch eSystem As NullReferenceException 'catch system exception and message
    MessageBox.Show("Please enter a numeric value greater than zero in all textboxes and" & _
    ControlChars.CrLf & "be sure you clicked the 'Create Better .. button" & _
    ControlChars.CrLf & " before pressing this 'Display Better... button" & _
    ControlChars.CrLf & "and you did not hit the 'Create Standard... button first.")

    End Try
    End Sub

    Private Sub btnCheckOil_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCheckOilStandard.Click


    Dim OilLevel As Single
    Try 'try.. catch
    OilLevel = CSng(txtOilLevel.Text)
    MyCar.Check_Oil(OilLevel) 'call to Class method


    Catch eSystem As InvalidCastException
    MessageBox.Show("You must enter values in all the textboxes and " _
    & ControlChars.CrLf & "click the 'Create' button before using this control")

    End Try
    End Sub
    Public Sub MyBetterCar_LowOil() Handles MyBetterCar.LowOil 'Event handler

    MessageBox.Show("Your oil level is low!" & ControlChars.CrLf & _
    "You need to add more oil", "Low Oil", MessageBoxButtons.OK, _
    MessageBoxIcon.Warning)

    Me.ClearText()

    End Sub
    Public Sub MyBetterCar_OilGood() Handles MyBetterCar.OilGood 'Event handler

    MessageBox.Show("Your oil level is OK.", "Level Good", _
    MessageBoxButtons.OK, MessageBoxIcon.Information)
    Me.ClearText()

    End Sub
    Public Sub MyCar_LowOil() Handles MyCar.LowOil 'Event handler

    MessageBox.Show("Your oil level is low!" & ControlChars.CrLf & _
    "You need to add more oil", "Low Oil", MessageBoxButtons.OK, _
    MessageBoxIcon.Warning)
    Me.ClearText()

    End Sub
    Public Sub MyCar_OilGood() Handles MyCar.OilGood 'Event handler

    MessageBox.Show("Your oil level is OK.", "Level Good", _
    MessageBoxButtons.OK, MessageBoxIcon.Information)
    Me.ClearText()

    End Sub

Page 1 of 2 12 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width