Introduction
This code should help solve an old topic in a smart way I think.
Requirement for this is a ListView
configured as follows:
required:
optional:
GridLines = True
FullRowSelect = True
Background
- Dynamical Creation of Controls in case
textBox
- Dynamical Addition of Handlers
Using the Code
I'm working with SharpDevelop 4.2, Framework 4.0 and used the Event "MouseDoubleClick
" of the ListView1
.
Here is my code:
Sub ListView1MouseDoubleClick(sender As Object, e As MouseEventArgs)
Dim RowColumn As Integer() = GET_RowColumn(listView1, New Point(e.X, e.Y))
Dim TmpTXT1 As New TextBox
listView1.Controls.Add(TmpTXT1)
With TmpTXT1
.Location = New Point(e.X, e.Y)
.Size = New Size(100, 23)
If listView1.Items.Item(RowColumn(0)).SubItems.Count - 1 >= RowColumn(1) Then
.Text = listView1.Items.Item(RowColumn(0)).SubItems.Item(RowColumn(1)).Text
Else
Do While listView1.Items.Item(RowColumn(0)).SubItems.Count <= RowColumn(1)
listView1.Items.Item(RowColumn(0)).SubItems.Add("")
Loop
.Text = listView1.Items.Item(RowColumn(0)).SubItems.Item(RowColumn(1)).Text
End If
.Show()
.BringToFront()
.Focus()
.SelectAll()
AddHandler .PreviewKeyDown, AddressOf TmpTXT1_PreviewKeyDown
AddHandler .LostFocus, AddressOf TmpTXT1_LostFocus
End With
End Sub
Function GET_RowColumn(ByVal LView As ListView, ByVal Position As Point) As Integer()
Dim TmpHTI1 As ListViewHitTestInfo = LView.HitTest(Position)
Dim RowColumn(2) As Integer
RowColumn(0) = TmpHTI1.Item.Index
RowColumn(1) = TmpHTI1.Item.SubItems.IndexOf(TmpHTI1.SubItem)
Return RowColumn
End Function
Sub TmpTXT1_PreviewKeyDown(ByVal sender As Object, ByVal e As PreviewKeyDownEventArgs)
Dim TmpTXT1 As TextBox = CType(sender, TextBox)
Dim RowColumn As Integer() = GET_RowColumn(listView1, TmpTXT1.Location)
If e.KeyCode = Keys.Enter Then
listView1.Items.Item(RowColumn(0)).SubItems.Item_
(RowColumn(1)).Text = CType(sender, TextBox).Text
CType(sender, TextBox).dispose()
ElseIf e.KeyCode = Keys.Escape Then
CType(sender, TextBox).dispose()
End If
End Sub
Sub TmpTXT1_LostFocus(ByVal sender As Object, ByVal e As EventArgs)
CType(sender, TextBox).dispose()
End Sub
History
- Version 1.0
- Version 1.1 - Added a loop which creates new empty SubItem(s) automatically 'OnClick' to prevent Exceptions with ListViewItems which have no SubItem yet. Thanks to BertrandLQ
- Version 1.2 - Found out that the previous Version of the Function
GET_RowColumn
does not work correctly with ListViews which are scrolled horizontal (e.g. small window but a big table width). ListViewHitTestInfo
finds the visual position of a ListViewItem
and gives the correct Row/Column Index back regardless of scrolling the ListView
horizontal or not.