Remove item from array

Hi,

I store courses in an array and then display it in listbox.I also count courses enrolled.That part perfectly works.Now i need to remove the course from the array.
Need Help ! Sorry new to VB.NET just started

~Thanx
anitha_rajAsked:
Who is Participating?
 
S-TwilleyCommented:
how are you counting the courses?

how are you adding the items to the array?

============================

a quick way to check that your enrolled courses array is correct...

              myStudent.enrolledCourse = y
              lstboxEnroll.Items.Remove(selItem)
                MsgBox(selItem)

change this to...


              myStudent.enrolledCourse = y
                lstboxEnroll.Items.Remove(selItem)
                MsgBox(selItem)

              Dim testStr as string = string.join("  || ", myStudent.enrolledCourse )
             Msgbox testStr

and then see if there are any entries that appear empty
0
 
S-TwilleyCommented:
is it just a normal array of strings? or an arraylist?

when you come to removing an item... what do you want?  for instance... do you want to remove a course from the list given its coursecode?  or position in the list?
0
 
anitha_rajAuthor Commented:
I use normal array to add course in the listbox.The hightlighted course in the listbox should be removed.
0
Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
S-TwilleyCommented:
Is the listbox sorted in anyway?
Does your array/listbox contain duplicate items?
0
 
S-TwilleyCommented:
Here's a sample for working with an array:


        Dim x() As String = {"A", "B", "C", "D", "E"}     ' your source array

        Dim iPos As Integer = Array.IndexOf(x, "E")     ' finds the index of the object you want to remove

        If iPos >= 0 Then                                          ' if the object is present
            Dim y(x.Length - 2) As String                      ' create an array which is slightly smaller than the source array

            Array.Copy(x, 0, y, 0, iPos)                          'copy all items from the source array to destination array up to (but not including) the questioned item
            Array.Copy(x, iPos + 1, y, iPos, (x.Length - 1 - iPos))   ' copy all items from source array to destination arrray after question item

            Dim s As String = ""

            For Each s In y                                            '
                MsgBox(s)                                               '     display each item in destination array
            Next
        End If

==============================

However, in your case we're working on the selected item in a listbox... I'll post up some samples in a moment that you can work with
0
 
S-TwilleyCommented:
   Dim x() As String = {"A", "B", "C", "D", "E"}     ' This will be like the array which holds your courses

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        ListBox1.Items.AddRange(x)                       ' just a button to load the initial array into a listbox
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click      ' THE DELETE BUTTON

        'GETS REFERENCE TO SELECTED ITEM
        Dim selItem As Object = ListBox1.SelectedItem

        If selItem Is Nothing Then
            'IF NO ITEM SELECTED
            'do nothing
        Else
           
            ' CHECKS TO SEE IF SELECTED ITEM IN LISTBOX IS IN YOUR ORIGINAL ARRAY
            Dim iPos As Integer = Array.IndexOf(x, selItem)     ' finds the index of the object you want to remove           '


            If iPos >= 0 Then                                        
                ' IF ITS PRESENT
                Dim y(x.Length - 2) As String                    

                ' CREATE A NEW ARRAY WITH SELECTED ITEM MISSING
                Array.Copy(x, 0, y, 0, iPos)                          
                Array.Copy(x, iPos + 1, y, iPos, (x.Length - 1 - iPos))  

                'REPLACE SOURCE ARRAY WITH NEW ARRAY
                x = y
 
                'RELOAD LISTBOX WITH SOURCE ARRAY
                ListBox1.Items.Clear()
                ListBox1.Items.AddRange(x)
            End If
        End If
    End Sub
0
 
anitha_rajAuthor Commented:
I use bubble sort
0
 
anitha_rajAuthor Commented:
No duplicate items.I have done validation
0
 
S-TwilleyCommented:
no probs... the code i posted up should be ok then... even if the items in the listbox are in a different order from the source array... it removes the object from the source array based on the object itself (and not the index within the listbox... which wouldn't work since they're out of sync)... it then reloads based on the source array... you could probably just remove the selected item from the listbox rather than reloading it ... was a a bit lapse minded of myself there, but at least you can be sure that they're displaying the same set of data.

================================

an alternative:

   Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click      ' THE DELETE BUTTON

        'GETS REFERENCE TO SELECTED ITEM
        Dim selItem As Object = ListBox1.SelectedItem

        If selItem Is Nothing Then
            'IF NO ITEM SELECTED
            'do nothing
        Else
           
            ' CHECKS TO SEE IF SELECTED ITEM IN LISTBOX IS IN YOUR ORIGINAL ARRAY
            Dim iPos As Integer = Array.IndexOf(x, selItem)     ' finds the index of the object you want to remove           '


            If iPos >= 0 Then                                        
                ' IF ITS PRESENT
                Dim y(x.Length - 2) As String                    

                ' CREATE A NEW ARRAY WITH SELECTED ITEM MISSING
                Array.Copy(x, 0, y, 0, iPos)                          
                Array.Copy(x, iPos + 1, y, iPos, (x.Length - 1 - iPos))  

                'REPLACE SOURCE ARRAY WITH NEW ARRAY
                x = y
                ListBox1.Items.Remove(selItem)
            End If
        End If
    End Sub
0
 
anitha_rajAuthor Commented:
I will try and see.Thank u
0
 
S-TwilleyCommented:
ANOTHER ALTERNATIVE... this removes the item from the listbox, then copies the items from the listbox back into the source array:

    Dim x() As String = {"D", "A", "E", "B", "C"}

   'LOADS LIST WITH ITEMS FROM ARRAY X
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click  
        ListBox1.Items.Clear()
        ListBox1.Items.AddRange(x)
        ListBox1.Sorted = True
    End Sub

    'DELETES SELECTED ITEM
    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        Dim selItem As Object = ListBox1.SelectedItem
        If selItem Is Nothing Then
            'do nothing
        Else
            ListBox1.Items.Remove(selItem)
            ReDim x(ListBox1.Items.Count - 1)
            ListBox1.Items.CopyTo(x, 0)
        End If
    End Sub

=============================

The difference between this one, and my previous samples is that this one makes changes to the Listbox, and then makes the source array reflect the contents of the listbox.

The previous one... made changes to the source array and listbox, and they both should reflect each other

.. and the one before last... made changes to the source array, and made the listbox reflect the contents of the source array... phew
0
 
S-TwilleyCommented:
... and i should say... this assumes your source array is a string array... if it isn't... let me know
0
 
anitha_rajAuthor Commented:
Which One is better?
0
 
anitha_rajAuthor Commented:
Yes my array is a string array
0
 
S-TwilleyCommented:
well they're all pretty similar... I guess it's down to what you'd prefer... do you understand the difference between the 3?
0
 
anitha_rajAuthor Commented:
I am new to VB.NET,so i never came across the word Array.Copy
0
 
S-TwilleyCommented:
Array.Copy just copies items from one array to another... it's a quick way of doing a For.Next loop to copy each item from one array to another
0
 
anitha_rajAuthor Commented:
Thank U
0
 
anitha_rajAuthor Commented:
Hi it just remove the item from listbox not from array
0
 
S-TwilleyCommented:
in the code i provided it does from the item from the array...  it's probably in your converting it to be used in your application that the problem has come up... if you post up the code you are using now, i'll see where the problem is
0
 
anitha_rajAuthor Commented:
Private Sub btnDrop_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDrop.Click
        Dim courses() As String = myStudent.courses.Split(",")

        'GETS REFERENCE TO SELECTED ITEM
        Dim selItem As Object = lstboxEnroll.SelectedItem

        If selItem Is Nothing Then
            'IF NO ITEM SELECTED
            'do nothing
        Else

            ' CHECKS TO SEE IF SELECTED ITEM IN LISTBOX IS IN YOUR ORIGINAL ARRAY
            Dim iPos As Integer = Array.IndexOf(courses, selItem)     ' finds the index of the object you want to remove           '


            If iPos >= 0 Then
                ' IF ITS PRESENT
                Dim y(courses.Length - 2) As String

                ' CREATE A NEW ARRAY WITH SELECTED ITEM MISSING
                Array.Copy(courses, 0, y, 0, iPos)
                Array.Copy(courses, iPos + 1, y, iPos, (courses.Length - 1 - iPos))

                'REPLACE SOURCE ARRAY WITH NEW ARRAY
                courses = y
                'lstboxEnroll.Items.Remove(selItem)
                MsgBox(selItem)
            End If
        End If



    End Sub
0
 
S-TwilleyCommented:
Private Sub btnDrop_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDrop.Click
        Dim courses() As String = myStudent.courses.Split(",")

        'GETS REFERENCE TO SELECTED ITEM
        Dim selItem As Object = lstboxEnroll.SelectedItem

        If selItem Is Nothing Then
            'IF NO ITEM SELECTED
            'do nothing
        Else

            ' CHECKS TO SEE IF SELECTED ITEM IN LISTBOX IS IN YOUR ORIGINAL ARRAY
            Dim iPos As Integer = Array.IndexOf(courses, selItem)     ' finds the index of the object you want to remove           '


            If iPos >= 0 Then
                ' IF ITS PRESENT
                Dim y(courses.Length - 2) As String

                ' CREATE A NEW ARRAY WITH SELECTED ITEM MISSING
                Array.Copy(courses, 0, y, 0, iPos)
                Array.Copy(courses, iPos + 1, y, iPos, (courses.Length - 1 - iPos))

                'REPLACE SOURCE ARRAY WITH NEW ARRAY

                myStudent.courses = String.Join(",",  y)  ' you were updating the array... but the array wasn't the true value of courses within the class
                lstboxEnroll.Items.Remove(selItem)
                MsgBox(selItem)
            End If
        End If
    End Sub
0
 
anitha_rajAuthor Commented:
it shows error in this particular line
                myStudent.courses = String.Join(",", y)   ' you were updating the array... but the array wasn't the true value of courses within the class
Shows the following error;Expression is a value therefore cannot be the target of an assignment
0
 
S-TwilleyCommented:
Is courses a read only property ?

If so, how are you supposed to update it?
0
 
anitha_rajAuthor Commented:
no i got course from a textbox

The below is my enroll course
Dim courses() As String = myStudent.courses.Split(",")
                myStudent.BubbleSort(courses)
                lstboxEnroll.Items.Clear()

                For Each str As String In courses
                    If str.Length > 0 Then
                        lstboxEnroll.Items.Add(str)
                    End If
                Next
0
 
S-TwilleyCommented:
you misunderstand...  the sources property i.e.  myStudent.courses  ... is that readonly.


AND on a side note... you can add an array of items to your listbox quickly using

Dim courses() As String = myStudent.courses.Split(",")
lstboxEnroll.Items.AddRange(courses)

although this will only work if there are no empty values in courses ( I think )
0
 
anitha_rajAuthor Commented:
OOps i didn't set any property for Course...I just have this following function only
Public Function courses() As String
        Dim returnVal As String = ""
        For i As Integer = 0 To enrolledCourse.Length - 1
            returnVal &= enrolledCourse(i) & ","
        Next
        Return returnVal
    End Function
0
 
S-TwilleyCommented:
SIDE NOTE 2:   :P

Public Function courses() As String
        Dim returnVal As String = String.Join(",", enrolledCourse)
        Return returnVal
End Function

' That should do the same in fewer lines


===============

if enrolledCourse is public... then

===============

Private Sub btnDrop_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDrop.Click
        Dim courses() As String = myStudent.courses.Split(",")

        'GETS REFERENCE TO SELECTED ITEM
        Dim selItem As Object = lstboxEnroll.SelectedItem

        If selItem Is Nothing Then
            'IF NO ITEM SELECTED
            'do nothing
        Else

            ' CHECKS TO SEE IF SELECTED ITEM IN LISTBOX IS IN YOUR ORIGINAL ARRAY
            Dim iPos As Integer = Array.IndexOf(courses, selItem)     ' finds the index of the object you want to remove           '


            If iPos >= 0 Then
                ' IF ITS PRESENT
                Dim y(courses.Length - 2) As String

                ' CREATE A NEW ARRAY WITH SELECTED ITEM MISSING
                Array.Copy(courses, 0, y, 0, iPos)
                Array.Copy(courses, iPos + 1, y, iPos, (courses.Length - 1 - iPos))

                'REPLACE SOURCE ARRAY WITH NEW ARRAY

                myStudent.enrolledCourse = y
                lstboxEnroll.Items.Remove(selItem)
                MsgBox(selItem)
            End If
        End If
    End Sub
0
 
anitha_rajAuthor Commented:
Yes it works! But my array count is wrong
0
 
S-TwilleyCommented:
where is it going wrong? i.e. where are you using that its coming out wrong?
0
 
anitha_rajAuthor Commented:
When i add course I count how many courses student had enrolled.That part works fine.But when i remove my course count stay the same as before
0
 
anitha_rajAuthor Commented:
there are empty entries
0
 
S-TwilleyCommented:
ok, then there were probably empty entries in the array to start with... how are you adding items to the enrolledCourse array... and  what is it's declaration?

i.e.

Public enrolledCourse() As String

=======

Basically, post up any code (other than my sub) where you are manipulating (adding / changing) items in the enrolledCourse array
0
 
anitha_rajAuthor Commented:
Public Function enroll(ByVal courseID As String) As Boolean

        If Not IsNothing(enrolledCourse) Then
            For Each str As String In enrolledCourse    '?
                If str = courseID Then
                    Return False
                End If
            Next
        End If

        ReDim Preserve enrolledCourse(lCourse_count + 1)
        enrolledCourse(lCourse_count) = courseID    '?
        lCourse_count += 1
        Return True

    End Function
0
 
S-TwilleyCommented:
and the declaration for enrolledCourse?
0
 
anitha_rajAuthor Commented:
   Public enrolledCourse() As String  'array is declared here
0
 
S-TwilleyCommented:
Public Function enroll(ByVal courseID As String) As Boolean
        If Not IsNothing(enrolledCourse) Then
            For Each str As String In enrolledCourse
                If str.ToLower = courseID.ToLower Then
                    Return False
                End If
            Next
        End If

        Dim currLength As Integer

        If enrolledCourse Is Nothing  Then
            currLength = 0
        Else
            currLength = enrolledCourse.Length
        End If

        ReDim Preserve enrolledCourse(currLength)
        enrolledCourse(currLength) = courseID
        Return True
End Function
0
 
anitha_rajAuthor Commented:
The problem is when i add for the second time only course count starts
0
 
S-TwilleyCommented:
To get  the course count... use

enrolledCourse.Length

=========================
0
 
anitha_rajAuthor Commented:
But still all this coding leads my previous problem when i delet a course my count remains the same
0
 
anitha_rajAuthor Commented:
Hello friend done it works
0
 
anitha_rajAuthor Commented:
Now i have few doubts
I didn't understand this part

' CREATE A NEW ARRAY WITH SELECTED ITEM MISSING
                Array.Copy(courses, 0, y, 0, iPos)
                Array.Copy(courses, iPos + 1, y, iPos, (courses.Length - 1 - iPos))
0
 
anitha_rajAuthor Commented:
and this one as well
  Public Function courses() As String
        Dim returnVal As String = String.Join(",", enrolledCourse)
        Return returnVal
    End Function

Can u explain it to me
0
 
S-TwilleyCommented:


Say you have an array:        0     1     2       3      4
                                      {  A  ,  D   , C   ,  F  ,   E  }


you want to  remove D... which is at index 1

you copy elements starting from 0, up to but not including element number 1
Array.Copy(courses, 0, y, 0, iPos)       '  iPos = 1


then you copy elements starting from 2, up to the end
Array.Copy(courses, iPos + 1, y, iPos, (courses.Length - 1 - iPos))    ' iPos = 1
0
 
S-TwilleyCommented:
Array.Copy has this structure

Array.Copy(ArrayCopyingFrom,  PositionToStartCopyingFrom,  ArrayCopyingTo, PositionToStartCopyingTo,   NumberOfItemsToCopy)
0
 
S-TwilleyCommented:
Public Function courses() As String
        Dim returnVal As String = String.Join(",", enrolledCourse)
        Return returnVal
    End Function

================

String.Join(ItemSeperator, Array) .... it joins an array into a string, seperating each item with ItemSeperator
0
 
anitha_rajAuthor Commented:
Thank You so much for answering me patiently
0
 
S-TwilleyCommented:
No problem
0
 
anitha_rajAuthor Commented:
Hi,
All these codes is for my assignment.IS there any way to remove this topic.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.