Solved

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

Posted on 2016-08-31
4
48 Views
Last Modified: 2016-09-12
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
Comment
Question by:Rob Rudloff
  • 2
4 Comments
 
LVL 39

Accepted Solution

by:
Kyle Abrahams earned 500 total points
Comment Utility
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
 
LVL 32

Expert Comment

by:it_saige
Comment Utility
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
 

Author Closing Comment

by:Rob Rudloff
Comment Utility
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
 
LVL 39

Expert Comment

by:Kyle Abrahams
Comment Utility
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

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

Welcome my friends to the second instalment and follow-up to our Minify and Concatenate Your Scripts and Stylesheets (http://www.experts-exchange.com/Programming/Languages/.NET/ASP.NET/A_4334-Minify-and-Concatenate-Your-Scripts-and-Stylesheets.html)…
If you need to start windows update installation remotely or as a scheduled task you will find this very helpful.
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now