Results 1 to 9 of 9

Thread: Checked List Boxes

Hybrid View

  1. #1
    New Member
    Join Date
    Aug 12
    Posts
    5

    Checked List Boxes

    A few things here. I am completely new to Visual Basic, in fact I am completely new to the wonderful world of programming(and forums for that matter).

    Question one, this may seem dumb, but I am using Visual Basic on Visual Studio 2010 Professional; does that mean I am using Visual Basic.Net?

    Question two:
    I am playing with Checked List boxed in Windows forms for a gas price comparison project(assigned in my Intro to Problem Solving in Programming class that has not gone over half of the things I am playing with in this project).

    I have created a checked list box, named it chkLstDiscounts (is that the correct conventional prefix?), and I entered the components Discount 1, Discount 2, and Discount 3.

    In my code I am attempting to use each individual component as follows:
    If (Discount 1 is checked) then
    perform discount
    EndIf
    If (Discount 2 is checked) then
    perform discount
    EndIf
    If (Discount 3 is checked) then
    perform discount
    EndIf

    My question is what do I put in my if statement where I say "Discount X is checked".
    So far I have found out that "chkLstDiscounts.CheckOnClick" will perform my calculations if ANY of the components are checked.

    I have a button that will need to make these components checked or unchecked, how do I perform this.
    Thanks for any and all advice.

  2. #2
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 02
    Location
    Bristol, UK
    Posts
    35,562

    Re: Checked List Boxes

    Welcome to VBForums

    Quote Originally Posted by The Han View Post
    Question one, this may seem dumb, but I am using Visual Basic on Visual Studio 2010 Professional; does that mean I am using Visual Basic.Net?
    It is VB.Net, but it isn't surprising that you weren't sure - Microsoft have been avoiding the name for a few years (these days they just call it VB, but make no secret that you need the .Net framework to use it or the programs it creates).

    I have therefore moved this thread to the 'VB.Net' (VB2002 and later) forum.

  3. #3
    New Member
    Join Date
    Jul 12
    Posts
    13

    Re: Checked List Boxes

    The Han, having been in the same boat as you a few months ago, I understand how it feels.

    First, I'm assuming that the "perform discount" part in your code block is a placeholder for each code based on which discount checkbox is picked?

    Second, chkLstDiscounts.CheckOnClick is not an event handler, it is a property. Instead you can just double click on the box in design mode and the event handler for if any checkbox is selected, then use a case statement or if-then statements to hold code for which checkbox is checked (The whole thing may be easier using simple checkboxes instead of CheckedListBox as they have individual event handlers). If you double click the box you should see this code:

    Code:
        Private Sub chkLstDiscounts_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkLstDiscounts.SelectedIndexChanged
    
        'Insert Code Here
    
        End Sub
    Now, for the logic to determine which was selected, one way is this: (I like case statements more than if-then)

    Code:
        Private Sub ChkLstDiscounts_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) _
            Handles chkLstDiscounts.SelectedIndexChanged
    
            Select Case chkLstDiscounts.SelectedItem.ToString
                Case "Discount 1"
                    'What you want to happen if Discount 1 is selected
                Case "Discount 2"
                    'What you want to happen if Discount 2 is selected
                Case "Discount 3"
                    'What you want to happen if Discount 3 is selected
            End Select
    
        End Sub
    You can also use chkLstDiscounts.SelectedItems to figure out if more than one is selected. If only one can be selected at a time, use radio boxes instead.

    Learning vb.net may feel like it will take forever to figure out, but once you get down logic and design (which really doesn't take that long), simple UI applications are very simple. I found it really helps to find many different types of free tutorials and take the time to complete them, then make sure you understand what occurs on every line of code. Hope that at least helps a little...

  4. #4
    New Member
    Join Date
    Jul 12
    Posts
    13

    Re: Checked List Boxes

    Sorry, just caught your last lines, are you saying you want a button to clear the checks, or a button that checks them for you after you have selected the checkboxes you want to be selected?

    Also, just to clarify, in my above code, chkLstDiscounts.SelectedItem.ToString has a string value of "Discount X", you should stick to your if statements though if you want multiple discounts (or whatever each code snippet does) to occur when more than one is selected (also need to use a button w/ click event handler otherwise each time you select a checkbox a discount may be applied even if it has been before).

  5. #5
    PowerPoster stanav's Avatar
    Join Date
    Jul 06
    Location
    Providence, RI - USA
    Posts
    9,167

    Re: Checked List Boxes

    How do you populate your CheckedListBox? And how do you relate "Discount 1" to an actual discount percentage or amount?
    Normally, I'd create a Discount class with corresponding properties, i.e DisplayMember and ValueMember. To populate the checkedlistbox, i'd create a collection of Discount objects and bind that to the checkedlistbox.
    The CheckedListBox has the CheckedItems property which returns a collection of the items being checked in it. You can also use the CheckedIndices, which returns a collection of the cheked items' indices. Note that if the checkedlistbox's CheckedOnClick property is False, those CheckedItems and CheckedIndices will include items that are in intermediate state also.
    Let us have faith that right makes might, and in that faith, let us, to the end, dare to do our duty as we understand it.
    - Abraham Lincoln -

  6. #6
    PowerPoster stanav's Avatar
    Join Date
    Jul 06
    Location
    Providence, RI - USA
    Posts
    9,167

    Re: Checked List Boxes

    Here is a quick example I put together for you. You need a form (Form1), a CheckedListBox (CheckedListBox1) and a Button (Button1).
    Code:
    Public Class Form1
        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            Dim discounts As New List(Of Discount)
            discounts.Add(New Discount("Discount 1", Discount.DiscountTypes.Percentage, 0.1D, 0D))                  '10% discount - no min purchase
            discounts.Add(New Discount("Discount 2", Discount.DiscountTypes.DollarAmount, 5D, 5D))                  '$5.00 discount, min $5 purchase
            discounts.Add(New Discount("Discount 3", Discount.DiscountTypes.DollarOffPerXPurchased, 25D, 50D))      '$25.00 discount with min purchase of $50.00
            CheckedListBox1.CheckOnClick = True
            CheckedListBox1.Items.AddRange(discounts.ToArray)
        End Sub
    
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            Dim totalPurchased As Decimal = 99.03D
            Dim totalDiscount As Decimal = CalculateDiscounts(totalPurchased)
            MessageBox.Show(String.Format("Total purchase: {0}{3}Total discount: {1}{3}Net Due: {2}", _
                                          totalPurchased.ToString("C"), totalDiscount.ToString("C"), _
                                          (totalPurchased - totalDiscount).ToString("C"), Environment.NewLine))
    
        End Sub
    
        Public Function CalculateDiscounts(ByVal purchaseAmount As Decimal) As Decimal
            'You should have your own rules on how to calculate multiple discounts, i.e discount type precedence,
            'should the discount amount be taken off the purchase amount before applying the next discount...
            'In this example, I just do a simple discount by applying all discounts in whatever order theuy come in
            Dim discountAmount As Decimal = 0D
            Dim discountValue As Decimal = 0D
            Dim requiredAmt As Decimal = 0D
            For Each itm As Discount In CheckedListBox1.CheckedItems
                discountValue = itm.DiscountValue
                requiredAmt = itm.RequiredPurchaseAmount
                Select Case itm.DiscountType
                    Case Discount.DiscountTypes.DollarAmount
                        If purchaseAmount >= discountAmount Then
                            discountAmount += discountValue
                            purchaseAmount -= discountValue
                        Else
                            discountAmount += purchaseAmount
                            purchaseAmount = 0D
                        End If
                    Case Discount.DiscountTypes.DollarOffPerXPurchased
                        If purchaseAmount >= requiredAmt Then
                            discountAmount += discountValue
                            purchaseAmount -= discountValue
                        End If
                    Case Discount.DiscountTypes.Percentage
                        discountAmount += purchaseAmount * discountValue
                        purchaseAmount -= purchaseAmount * discountValue
                    Case Discount.DiscountTypes.PercentOffPerXPurchased
                        If purchaseAmount >= requiredAmt Then
                            discountAmount += purchaseAmount * discountValue
                            purchaseAmount -= purchaseAmount * discountValue
                        End If
                End Select
            Next
            Return discountAmount
        End Function
    
        Public Class Discount
            Public Enum DiscountTypes
                Percentage              'percent off the total purchase.
                PercentOffPerXPurchased 'percent off applied only when min purchase of X dollars reached.
                DollarAmount            'fixed dollar amount off the entire purchase
                DollarOffPerXPurchased  'fixed dollar amount off applied only when min purchase of X dollars reached
                'And so on....
            End Enum
    
            Public Property DiscountName() As String
            Public Property DiscountValue() As Decimal
            Public Property DiscountType As Discount.DiscountTypes
            Public Property RequiredPurchaseAmount As Decimal
    
            Public Sub New(ByVal txt As String, ByVal discntType As Discount.DiscountTypes, ByVal discount As Decimal, ByVal minPurchase As Decimal)
                Me.DiscountName = txt
                Me.DiscountType = discntType
                Me.DiscountValue = discount
                Me.RequiredPurchaseAmount = minPurchase
            End Sub
    
            Public Overrides Function ToString() As String
                Return String.Format("{0} - {1}: {2}", Me.DiscountName, Me.DiscountType.ToString, Me.DiscountValue.ToString("N2"))
            End Function
    
        End Class
    End Class
    Let us have faith that right makes might, and in that faith, let us, to the end, dare to do our duty as we understand it.
    - Abraham Lincoln -

  7. #7
    New Member
    Join Date
    Jul 12
    Posts
    13

    Re: Checked List Boxes

    Please make sure that you know exactly what @stanav 's code does, instead of cut/paste. I started out doing that (cut/paste technique) only to have to actually learn the logical flow when debugging even the smallest problems. It really does create less headache to learn it from the beginning, rather than create an entire program and not know how it does what it does.

  8. #8
    vb Coda .paul.'s Avatar
    Join Date
    May 07
    Location
    Chelmsford UK
    Posts
    16,471

    Re: Checked List Boxes

    @stanav. good answer. i'm sure you know but:

    this:

    vb Code:
    1. MessageBox.Show(String.Format("Total purchase: {0}{3}Total discount: {1}{3}Net Due: {2}", _
    2.                                       totalPurchased.ToString("C"), totalDiscount.ToString("C"), _
    3.                                       (totalPurchased - totalDiscount).ToString("C"), Environment.NewLine))

    can be more efficiently written as this:

    vb Code:
    1. MessageBox.Show(String.Format("Total purchase: {0:C}{3}Total discount: {1:C}{3}Net Due: {2:C}", _
    2.                               totalPurchased, totalDiscount, _
    3.                               (totalPurchased - totalDiscount), Environment.NewLine))

  9. #9
    New Member
    Join Date
    Aug 12
    Posts
    5

    Re: Checked List Boxes

    Sorry it took me so long to update.
    I haven't examined your posts yet, too tired to think and I got a little confused.

    I am attaching a copy of the project I am turning in, Its quite rough but it does more than the class assignment asked for.

    In the attached project I went with seperate checkboxes, I would like to learn how to make these into checked list boxes in this instance(two different boxes, one for each station).

    Thanks for all the input so far(I look forward to reading your posts, when I can)
    Attached Files Attached Files

Posting Permissions

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