ListView selected item position

R

RickN

I would like to find an item in my listview items collection and have it
scroll to the 3rd visible item in the list and be marked as selected.
What's the best way to do this?

Thanks,
RickN
 
H

Herfried K. Wagner [MVP]

* "RickN said:
I would like to find an item in my listview items collection and have it
scroll to the 3rd visible item in the list and be marked as selected.
What's the best way to do this?

Maybe setting the item's 'Selected' property and calling its
'EnsureVisible' method will do the job for you.
 
R

RickN

I do that already, but if the item was below the visible boundaries of the
listview, it just moves it to the last visible position. I am trying to
designate it as the 3rd (or whatever) visible item in the list.

RickN
 
P

Palo Mraz

I do that already, but if the item was below the visible boundaries of the
listview, it just moves it to the last visible position. I am trying to
designate it as the 3rd (or whatever) visible item in the list.

Rick, checkout the following code. It uses P/Invoke to send the LVM_SCROLL
message to the ListView and it works just in the Details view...


<System.Runtime.InteropServices.DllImport("User32.dll")> _
Private Shared Function SendMessage _
(ByVal hWnd As IntPtr, ByVal Msg As Integer, _
ByVal wParam As Integer, ByVal lParam As Integer) As IntPtr
End Function

'#define LVM_SCROLL (LVM_FIRST + 20)
'#define LVM_FIRST 0x1000 // ListView messages
Private Const LVM_FIRST As Integer = &H1000
Private Const LVM_SCROLL As Integer = LVM_FIRST + 20


Private Sub ShowItem(ByVal item As ListViewItem, ByVal indexFromTop As
Integer)
Try
item.ListView.BeginUpdate()

' Select the item in question and ensure it is in the visible portion
of the ListView.
item.Selected = True
item.EnsureVisible()

' Calculate the distance between the topmost item and the selected
item.
Dim Distance As Integer = item.Index - item.ListView.TopItem.Index -
(indexFromTop - 1)

' Calculate the line height for one item; this is needed because
LVM_SCROLL works in
' pixels, not in lines.
Dim ItemLineHeight As Integer = item.Bounds.Height

' Calculate the neccessary amount of scrolling and scroll te ListView.
Dim ScrollAmountPixels As Integer = (Distance * ItemLineHeight)
Dim Result As IntPtr = SendMessage(item.ListView.Handle, LVM_SCROLL,
0, ScrollAmountPixels)
Finally
item.ListView.EndUpdate()
End Try
End Sub
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top