Solved

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

Posted on 2016-08-31
4
57 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
4 Comments
 
LVL 40

Accepted Solution

by:
Kyle Abrahams earned 500 total points
ID: 41778663
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 34

Expert Comment

by:it_saige
ID: 41778679
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
ID: 41786474
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 40

Expert Comment

by:Kyle Abrahams
ID: 41786482
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

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In my previous two articles we discussed Binary Serialization (http://www.experts-exchange.com/A_4362.html) and XML Serialization (http://www.experts-exchange.com/A_4425.html). In this article we will try to know more about SOAP (Simple Object Acces…
If you need to start windows update installation remotely or as a scheduled task you will find this very helpful.
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an antispam), the admini…

710 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