Link to home
Start Free TrialLog in
Avatar of Rob Rudloff
Rob RudloffFlag for United States of America

asked on

How to select the newest item/row in a listview?

I am new at VB.net, and have inherited the code for an old desktop app in use at my company...

I have a ListView that users can "add" rows to by clicking an "add" button, which calls the code below.

Is there a way to programmatically select the row/item that the user just added?  Perhaps there's a way to get the index of the "ListViewItem" immediately after it is Dim'd, then point to that row after the .Items.Add ?
Thanks.
Dim itmCart = New ListViewItem(HeaderID.ToString())
itmCart.SubItems.Add(lsCartNumber)
itmCart.SubItems.Add(lsUserID)
lstCarts.Items.Add(itmCart)

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Kyle Abrahams, PMP
Kyle Abrahams, PMP
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Use IndexOf; e.g. -

Form1.vb -
Public Class Form1
	Private Sub OnKeyUp(sender As Object, e As KeyEventArgs) Handles TextBox1.KeyUp
		If TypeOf sender Is TextBox Then
			Dim tb = DirectCast(sender, TextBox)
			If tb.Equals(TextBox1) Then
				If e.KeyData.Equals(Keys.Enter) AndAlso Not String.IsNullOrWhiteSpace(tb.Text) Then
					Dim item As New ListViewItem(tb.Text)
					ListView1.Items.Add(item)
					RichTextBox1.AppendText(String.Format("Added {0} to Listview at {1}{2}", item.Text, ListView1.Items.IndexOf(item), Environment.NewLine))
					tb.Clear()
				End If
			End If
		End If
	End Sub
End Class

Open in new window

Form1.Designer.vb -
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class Form1
    Inherits System.Windows.Forms.Form

    'Form overrides dispose to clean up the component list.
    <System.Diagnostics.DebuggerNonUserCode()> _
    Protected Overrides Sub Dispose(ByVal disposing As Boolean)
        Try
            If disposing AndAlso components IsNot Nothing Then
                components.Dispose()
            End If
        Finally
            MyBase.Dispose(disposing)
        End Try
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
    <System.Diagnostics.DebuggerStepThrough()> _
    Private Sub InitializeComponent()
		Me.ListView1 = New System.Windows.Forms.ListView()
		Me.TextBox1 = New System.Windows.Forms.TextBox()
		Me.RichTextBox1 = New System.Windows.Forms.RichTextBox()
		Me.SuspendLayout()
		'
		'ListView1
		'
		Me.ListView1.Location = New System.Drawing.Point(13, 39)
		Me.ListView1.Name = "ListView1"
		Me.ListView1.Size = New System.Drawing.Size(259, 210)
		Me.ListView1.TabIndex = 0
		Me.ListView1.UseCompatibleStateImageBehavior = False
		'
		'TextBox1
		'
		Me.TextBox1.Location = New System.Drawing.Point(13, 13)
		Me.TextBox1.Name = "TextBox1"
		Me.TextBox1.Size = New System.Drawing.Size(259, 20)
		Me.TextBox1.TabIndex = 1
		'
		'RichTextBox1
		'
		Me.RichTextBox1.Location = New System.Drawing.Point(13, 256)
		Me.RichTextBox1.Name = "RichTextBox1"
		Me.RichTextBox1.ReadOnly = True
		Me.RichTextBox1.Size = New System.Drawing.Size(259, 96)
		Me.RichTextBox1.TabIndex = 2
		Me.RichTextBox1.Text = ""
		'
		'Form1
		'
		Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
		Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
		Me.ClientSize = New System.Drawing.Size(284, 363)
		Me.Controls.Add(Me.RichTextBox1)
		Me.Controls.Add(Me.TextBox1)
		Me.Controls.Add(Me.ListView1)
		Me.Name = "Form1"
		Me.Text = "Form1"
		Me.ResumeLayout(False)
		Me.PerformLayout()

	End Sub
	Friend WithEvents ListView1 As System.Windows.Forms.ListView
	Friend WithEvents TextBox1 As System.Windows.Forms.TextBox
	Friend WithEvents RichTextBox1 As System.Windows.Forms.RichTextBox

End Class

Open in new window

Produces the following output -User generated image
-saige-
Avatar of Rob Rudloff

ASKER

Kyle --
Using that code, I got an error with the "[i]lstCarts.SelectedIndex =[/i]" part of the line:
     [i]Error 'SelectedIndex' is not a member of 'ListView'[/i]
So I looked at some of the other members of lstCarts, and did some reading and found that the ".Selected" property of an item will get or set the "selected" state.

So, using your note that the last item added has the highest index, I changed your line:
    [i] lstCarts.SelectedIndex = lstCarts.Items.Count() - 1[/i]
to
     [i]lstCarts.Items(lstCarts.Items.Count() - 1).Selected = True[/i]
and it works.

Next, I need to see how this all works when the listview is sorted.  I assume the index stays the same as the order it was added in ... Or perhaps the index changes when the items are sorted.

Thanks
I believe you are correct in that the index will stay the same.  

You can use a combination of the sorting / sorted event to get what you need:
https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listview_events(v=vs.110).aspx

sorting you would save the selected item (or value)
sorted you would reset the selected item based on the one found in sorting.