Results 1 to 10 of 10

Thread: [RESOLVED] selecting second item in a listview?!

  1. #1

    Thread Starter
    Junior Member
    Join Date
    Jul 2014
    Posts
    27

    Resolved [RESOLVED] selecting second item in a listview?!

    Hey guys!

    So I have a listview which displays one or multiple items according to a search textbox. For example if I search "John" in the textbox, it will display the ID, First Name and Last Name of all the entries with the first name John from a SQL database. Then when I select the or one of the items returned in the listview, it shows all the information about that particular person as well as a photo. That works just fine! My problem is that when I want to select another item in the listview (or if I just click anywhere else in the listview if only one item was returned), then the application crashes.

    cmd.Parameters.AddWithValue("@ID", ListView1.SelectedItems(0).Text) InvalidArgument = Value of 0 is not valid for "index"

    I'm not sure what to do to fix it.

    Thanks a bunch for helping!


    Code:
    Private Sub ListView1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListView1.SelectedIndexChanged
    
            
            Using conn As New SqlClient.SqlConnection("Data Source=JULIEN-PC\SQLEXPRESS;Initial Catalog=loginbeta;Integrated Security=True; MultipleActiveResultSets=true")
                conn.Open()
    
                'query database according to the ID# selected in listview
                Dim query As String = "SELECT ID, FirstName, LastName, Address, City, State, Zipcode, Phone, Position, email, Photo FROM Users_table WHERE ID = @ID"
                Dim cmd As New SqlClient.SqlCommand(query, conn)
                cmd.Parameters.AddWithValue("@ID", ListView1.SelectedItems(0).Text)
                Dim reader As SqlClient.SqlDataReader = cmd.ExecuteReader
    
    
                'return the corresponding values to the labels
                If reader.Read() Then
    
                    idtxt.Text = reader("ID").ToString()
                    fntxt.Text = reader("FirstName").ToString()
                    lntxt.Text = reader("LastName").ToString()
                    adresstxt.Text = reader("Address").ToString()
                    citytxt.Text = reader("City").ToString()
                    statetxt.Text = reader("State").ToString()
                    ziptxt.Text = reader("Zipcode").ToString()
                    teltxt.Text = reader("Phone").ToString()
                    postxt.Text = reader("Position").ToString()
                    emailtxt.Text = reader("email").ToString()
    
                    'query the photo from the database
                    Dim query1 As String = "SELECT Photo FROM Users_table  WHERE ID = @ID"
                    Dim command As New SqlClient.SqlCommand(query1, conn)
                    command.Parameters.AddWithValue("@ID", ListView1.SelectedItems(0).Text)
                    Dim data As Byte() = DirectCast(command.ExecuteScalar(), Byte())
                    Dim ms As New MemoryStream(data)
                    PictureBox1.Image = Image.FromStream(ms)
                    Me.PictureBox1.SizeMode = PictureBoxSizeMode.StretchImage
    
    
                End If
    
    
                reader.Close()
                conn.Close()
    
            End Using
     End Sub

  2. #2
    PowerPoster techgnome's Avatar
    Join Date
    May 2002
    Posts
    32,953

    Re: selecting second item in a listview?!

    If index 0 is invalid, then it's likely nothing is selected. You should check the .Count property of the array before trying to access it, make sure there's something there to read.

    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  3. #3

    Thread Starter
    Junior Member
    Join Date
    Jul 2014
    Posts
    27

    Re: selecting second item in a listview?!

    Thanks for helping! There is something to read because when I select the item in the listview (all three columns are selected), it displays all the corresponding info from the database in my labels. I just can't select another item. Thanks again for trying to help!

  4. #4
    PowerPoster techgnome's Avatar
    Join Date
    May 2002
    Posts
    32,953

    Re: selecting second item in a listview?!

    Sigh... set a break point and check... you may be surprised...

    Try this:
    New project, 1 form with a Button, ListView in Details view, and a multiline Textbox.
    Code:
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            For a = 1 To 10
                ListView1.Items.Add(New ListViewItem(a.ToString))
            Next
        End Sub
    
        Private Sub ListView1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListView1.SelectedIndexChanged
            TextBox1.Text &= "Items selected: " & ListView1.SelectedItems.Count.ToString & Environment.NewLine
            If ListView1.SelectedItems.Count > 0 Then
                TextBox1.Text &= "Selected Item Text: " & ListView1.SelectedItems(0).Text & Environment.NewLine
            End If
        End Sub
    This will load 10 items into the LV... then select one of them
    You should get this in the textbox:
    Code:
    Items selected: 1
    Selected Item Text: 1
    Now select something else.
    The textbox now looks like this:
    Code:
    Items selected: 1
    Selected Item Text: 1
    Items selected: 0
    Items selected: 1
    Selected Item Text: 4
    Woah! Look at that!
    Items selected: 0 <-- that means there was NOTHING in the SelectedItems array...

    Here's what's going on... you selected something. It gets added... then you select something else. First thing the LV does is to CLEAR out all of the previously selected items... this happens to cause the SelectedIndexChange to fire, but the SelectedItems array is empty... then after that, it adds the selected item back in, and fires the SelectedIndexChanged again...

    This is why I said to FIRST check to MAKE sure there's something in it... you assumed there was because you had selected something... but that wasn't the case... it first needed to CLEAR the selections first.

    Had you just taken 5 seconds to check it, you would have (hopefully) seen this happening... It's not like I was guessing at the problem. It's not like you're the first person to experience this issue.

    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  5. #5

    Thread Starter
    Junior Member
    Join Date
    Jul 2014
    Posts
    27

    Re: selecting second item in a listview?!

    I get what you're saying and it makes sense but I cant think of how to fix it with my code...Should I use

    ListView1.SelectedItems.Count > 0 ? Do I use it in the selectindexchanged handler?

    I'm sorry, I'm a beginner in vb.net and coding in general. Thank you for helping!

  6. #6
    PowerPoster techgnome's Avatar
    Join Date
    May 2002
    Posts
    32,953

    Re: selecting second item in a listview?!

    Yes and yes...

    you need to check that the .Count is greater than 0 before accessing any of the indexes in the array.

    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  7. #7

    Thread Starter
    Junior Member
    Join Date
    Jul 2014
    Posts
    27

    Re: selecting second item in a listview?!

    I'm sorry, I've tried multiple times but I can't figure it out =/ It's killing me!

    if ListView1.selecteditems.count > 0 then
    messagebox.show("item selected")

    I used the code above to see what would happen. When I click to select my first item in the listview, the messagebox would pop up. Then, when I tried selecting another item, it would crash. I modified the code to "> -1"
    After that, when I select another item, the messagebox pops up again....but the application still crashes right after that.

  8. #8
    PowerPoster techgnome's Avatar
    Join Date
    May 2002
    Posts
    32,953

    Re: selecting second item in a listview?!

    what does your actual code look like? I showed in the code I posted how it should be... if the count > 0 then you deal with it. If it isn't then you do nothing. I suspect it's still crashing because you're still doing something even with an empty array.

    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  9. #9
    PowerPoster techgnome's Avatar
    Join Date
    May 2002
    Posts
    32,953

    Re: selecting second item in a listview?!

    Ok... pulling your code from post #1
    Code:
    Private Sub ListView1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListView1.SelectedIndexChanged
    
        Dim UserID as string ' change to what ever is appropriate
        if ListView1.SelectedItems.Count > 0 then
            UserID = ListView1.SelectedItems(0).Text
    
    
            Using conn As New SqlClient.SqlConnection("Data Source=JULIEN-PC\SQLEXPRESS;Initial Catalog=loginbeta;Integrated Security=True; MultipleActiveResultSets=true")
                conn.Open()
    
                'query database according to the ID# selected in listview
                Dim query As String = "SELECT ID, FirstName, LastName, Address, City, State, Zipcode, Phone, Position, email, Photo FROM Users_table WHERE ID = @ID"
                Dim cmd As New SqlClient.SqlCommand(query, conn)
                cmd.Parameters.AddWithValue("@ID", UserID)
                Dim reader As SqlClient.SqlDataReader = cmd.ExecuteReader
    
    
                'return the corresponding values to the labels
                If reader.Read() Then
    
                    idtxt.Text = reader("ID").ToString()
                    fntxt.Text = reader("FirstName").ToString()
                    lntxt.Text = reader("LastName").ToString()
                    adresstxt.Text = reader("Address").ToString()
                    citytxt.Text = reader("City").ToString()
                    statetxt.Text = reader("State").ToString()
                    ziptxt.Text = reader("Zipcode").ToString()
                    teltxt.Text = reader("Phone").ToString()
                    postxt.Text = reader("Position").ToString()
                    emailtxt.Text = reader("email").ToString()
    
                    'query the photo from the database
                    Dim query1 As String = "SELECT Photo FROM Users_table  WHERE ID = @ID"
                    Dim command As New SqlClient.SqlCommand(query1, conn)
                    command.Parameters.AddWithValue("@ID", ListView1.SelectedItems(0).Text)
                    Dim data As Byte() = DirectCast(command.ExecuteScalar(), Byte())
                    Dim ms As New MemoryStream(data)
                    PictureBox1.Image = Image.FromStream(ms)
                    Me.PictureBox1.SizeMode = PictureBoxSizeMode.StretchImage
    
    
                End If
    
    
                reader.Close()
                conn.Close()
    
            End Using
    
         end if
    
     End Sub
    There... that's all there is to it... you check to see if there are items in the array, and if so, do what you need to do... if not... you skip over everything and bail.

    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  10. #10

    Thread Starter
    Junior Member
    Join Date
    Jul 2014
    Posts
    27

    Re: selecting second item in a listview?!

    Works like a charm! I can't thank you enough! It does seem very straightforward and simple now but I just couldn't think lol

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