locked
Providing index for item of checkedlistbox in for loop RRS feed

  • Question

  • Please excuse me if this is quite infantile as I just started trying to learn vb.net within the last couple weeks.  I am having a terrible time trying to find direction for this via google method.

    I'm trying to assign the text values of checked items within a checkedlistbox to an arraylist.

        Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
    
            Dim boxValues As ArrayList
            Dim itemChecked As Object
            Dim itemsChecked As Integer = CInt(NameCheckedListBox.CheckedItems.Count.ToString)
            Dim i As Integer
    
            For i = 0 To itemsChecked
                Dim c As Integer = i
                boxValues(i).Add = NameCheckedListBox.CheckedItems.Item(c)
            Next
    
        End Sub


    VBE debugger advises "Object reference not set to an instance of an object."

    I had originally used i as NameCheckedListBox.CheckedItems.Item(i) and debugger was giving the same error as far as I could tell.  

    Could anybody please correct me as how to assert the current value of i as the reference for NameCheckedListBox.CheckedItems.Item?



    • Edited by r.alvin Friday, November 9, 2012 4:06 AM
    Friday, November 9, 2012 4:05 AM

Answers

  • You haven't constructed boxValues, so it has the value "Nothing".  You can't use it until it's instantiated.

    It isn't necessary to convert an integer to a string and then to an integer to get an integer.  This is better code: 

    Dim itemsChecked As Integer = NameCheckedListBox.CheckedItems.Count.

    Friday, November 9, 2012 6:46 AM
  • You don't need two variables for the indexes. The maximum index value is always 1 less than the count.

            For i = 0 To itemsChecked - 1
                boxValues.Add = NameCheckedListBox.CheckedItems.Item(i)
           
    Next

    Friday, November 9, 2012 9:47 AM

All replies

  • You haven't constructed boxValues, so it has the value "Nothing".  You can't use it until it's instantiated.

    It isn't necessary to convert an integer to a string and then to an integer to get an integer.  This is better code: 

    Dim itemsChecked As Integer = NameCheckedListBox.CheckedItems.Count.

    Friday, November 9, 2012 6:46 AM
  • You don't need two variables for the indexes. The maximum index value is always 1 less than the count.

            For i = 0 To itemsChecked - 1
                boxValues.Add = NameCheckedListBox.CheckedItems.Item(i)
           
    Next

    Friday, November 9, 2012 9:47 AM