Solved

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

Posted on 2016-08-31
4
52 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 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 33

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

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

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

More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
This Micro Tutorial demonstrates using Microsoft Excel pivot tables, how to reverse engineer competitors' marketing strategies through backlinks.
Although Jacob Bernoulli (1654-1705) has been credited as the creator of "Binomial Distribution Table", Gottfried Leibniz (1646-1716) did his dissertation on the subject in 1666; Leibniz you may recall is the co-inventor of "Calculus" and beat Isaac…

803 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