Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 69
  • Last Modified:

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

0
Rob Rudloff
Asked:
Rob Rudloff
  • 2
1 Solution
 
Kyle AbrahamsSenior .Net DeveloperCommented:
After you add the item it's always at the end so just set the selectedindex:

lstCarts.SelectedIndex = lstCarts.Items.Count() - 1

Open in new window

0
 
it_saigeDeveloperCommented:
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 -Capture.JPG
-saige-
0
 
Rob RudloffIT Development SpecialistAuthor Commented:
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
0
 
Kyle AbrahamsSenior .Net DeveloperCommented:
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.
0

Featured Post

Configuration Guide and Best Practices

Read the guide to learn how to orchestrate Data ONTAP, create application-consistent backups and enable fast recovery from NetApp storage snapshots. Version 9.5 also contains performance and scalability enhancements to meet the needs of the largest enterprise environments.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now