|
|
|
Sometimes you might want to determine which listview column clicked by user. You can find listitem (i.e. row) using GetItemAt method but there is no direct property or method in .Net to determine clicked subitem (i.e. column) based on (X,Y) coordinates. Here is the small code snippet to accomplish this task.
Step-by-Step Example
- Create a Windows Application project - Add one listview control on the form1 - Add the following code in form1 |
Click here to copy the following block | Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load ListView1.FullRowSelect = True ListView1.HideSelection = False
ListView1.View = View.Details ListView1.Items.Clear()
Dim h0 As New ColumnHeader Dim h1 As New ColumnHeader Dim h2 As New ColumnHeader
h0.Text = "Col0" h1.Text = "Col1" h2.Text = "Col2"
ListView1.Columns.Add(h0) ListView1.Columns.Add(h1) ListView1.Columns.Add(h2)
For i As Integer = 0 To 10 With ListView1.Items.Add("Itm" & i & "-0") .SubItems.Add("Itm" & i & "-1") .SubItems.Add("Itm" & i & "-2") .SubItems.Add("Itm" & i & "-3") End With Next End Sub
Private Sub ListView1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles ListView1.MouseDown Dim col, row If GetListSubItemFromPoint(ListView1, e.X, e.Y, row, col) = True Then Me.Text = "Item# =>" & row & " ; Subitem# =>" & col Else MsgBox("Please click on subitem") End If End Sub
Function GetListSubItemFromPoint(ByVal lv As ListView, _ ByVal X As Integer, _ ByVal Y As Integer, _ Optional ByRef retRow As Integer = 0, _ Optional ByRef retCol As Integer = 0) As Boolean
Dim flag As Boolean Dim Item As ListViewItem Dim col, row As Integer
Try flag = lv.FullRowSelect
If flag = False Then lv.FullRowSelect = True If lv.Items.Count <= 0 And lv.Columns.Count > 0 Then
lv.BeginUpdate()
With ListView1.Items.Add(".") For col = 0 To lv.Columns.Count - 1 .SubItems.Add("..") Next Y = .GetBounds(ItemBoundsPortion.Label).Y End With Item = lv.GetItemAt(X, Y) row = -1 Else Item = lv.GetItemAt(X, Y) End If
lv.FullRowSelect = flag
If Not Item Is Nothing Then Dim I As Integer = 0 Dim R As Rectangle = Item.GetBounds(ItemBoundsPortion.Label) Do While I < Item.SubItems.Count If R.Contains(X, Y) Then retRow = IIf(row = -1, -1, Item.Index) retCol = I
GetListSubItemFromPoint = True Exit Do End If R.X = R.X + lv.Columns(I).Width R.Width = lv.Columns(I + 1).Width I = I + 1 Loop End If
Catch ex As Exception Finally If row = -1 Then lv.Items.Clear() lv.EndUpdate() End If End Try End Function |
|
|
|
Submitted By :
Nayan Patel
(Member Since : 5/26/2004 12:23:06 PM)
|
|
|
Job Description :
He is the moderator of this site and currently working as an independent consultant. He works with VB.net/ASP.net, SQL Server and other MS technologies. He is MCSD.net, MCDBA and MCSE. In his free time he likes to watch funny movies and doing oil painting. |
View all (893) submissions by this author
(Birth Date : 7/14/1981 ) |
|
|