Edit ListView SubItems

This example explains an easy way to edit ListView subitems. A double click on the ListView.SubItem will visualize a TextBox overlaying the SubItem with same size. The entered signs will be written to the SubItem after TextBox_LostFocus event was raised (by clicking on the ListView control or hit RETURN key).

The following Visual Basic code is to be inserted into a form (e.g. MainForm). The Form contains a TextBox, Button and ListView control. TextBox and Button are hidden ([control].Visible = False)

For the listview the following settings apply:

  • set ListView.FullRowSelect = True
  • set ListView.GridLines = True
  • set ListView.Details = True

Remark: The LostFocus will not be raised if you click on the form. It will be called when you click on another control such as the ListView.

The Code



'declare a global variable to store the column index
Private selCol As Integer

'create ListView structure during FormLoad Event
Private Sub MainForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load


        ListView42.Clear()

        ListView42.Columns.Add("Category")
        ListView42.Columns.Add("Monday")
        ListView42.Columns.Add("Tuseday")
        ListView42.Columns.Add("Wednesday")
        ListView42.Columns.Add("Thursday")
        ListView42.Columns.Add("Friday")
        ListView42.Columns.Add("Satturday")
        ListView42.Columns.Add("Sunday")
        ListView42.Columns.Add("Average")

        'load criteria column values into list view
        ListView42.Items.Add("quiet")
        ListView42.Items.Add("light")
        ListView42.Items.Add("medium")
        ListView42.Items.Add("intensive")
        ListView42.Items.Add("heavy")

        'create subitems
        'set the Tags for later identification of clicked subitem(index)
        For a = 0 To ListView42.Items.Count - 1
            For c = 1 To ListView42.Columns.Count - 1
                ListView42.Items(a).SubItems.Add(a & c).Tag = a & c
            Next
        Next
    End Sub


Private Sub ListView42_MouseDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles ListView42.MouseDoubleClick

        'detect clicked subitem / column
        Dim hit As ListViewHitTestInfo = ListView42.HitTest(e.X, e.Y)

        For Each lItem As ListViewItem In ListView42.Items
            If lItem.Selected = True Then
                For a = 0 To lItem.SubItems.Count
                    If hit.SubItem.Tag = lItem.SubItems(a).Tag Then
                        selCol = a
                        'prevent edit on first column
                        If selCol = 0 Then Exit Sub
                        'dim size and location of the TextBox
                        'TextBox.FontSize maybe 1 bigger than that of
                        'Listview Items to get the users eye catched on it.
                        TextBox42.Left = ListView42.Left + hit.SubItem.Bounds.Left + 3
                        TextBox42.Top = ListView42.Top + hit.SubItem.Bounds.Top
                        TextBox42.Width = hit.SubItem.Bounds.Width
                        TextBox42.Text = hit.SubItem.Text
                        'set TextBox to visible for user input
                        TextBox42.Visible = True
                        TextBox42.Focus()
                        TextBox42.SelectAll()
                        Exit For
                    End If
                Next
            End If
        Next
    End Sub


    Private Sub TextBox42_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox42.KeyPress

        'call LostFocus Sub in the event user pressed RETURN
        If e.KeyChar = Microsoft.VisualBasic.ChrW(Keys.Return) Then
            TextBox42_LostFocus(sender, Nothing)
        End If
    End Sub


    Private Sub TextBox42_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox42.LostFocus
       
        Dim selDetail As String

        'hide textbox
        TextBox42.Visible = False
        'load old value to detect if there is a change
        selDetail = ListView42.SelectedItems(0).SubItems(selCol).Text

        'change the subitem.text only if the new value is different to the existing one
        'to prevent display of the save butten without changing values
        If selDetail <> TextBox42.Text Then

  ListView42.Items(ListView42.SelectedItems(0).Index).SubItems(selCol).Text = TextBox42.Text

            'set change flag for not stored information to prevent loss of update by change of selection
            'changeFlage = True
            btnSave.Visible = True
        End If

        'do not clear the TextBox.Text, dueto LostFocus Sub may be called twice
        '(e.g. click mouse on a control different as the ListView)
        'else the list subitem.text will be overwritten again by an empty string

    End Sub

  


Downloads

Comments

  • An easier method for cell edit in listviews

    Posted by andlov on 09/30/2009 10:10pm

    Thanks, an nice article. The idea to use HitTest really pushed me in the right direction. 
    
    However, the code can be simplified by letting the listview be the textbox parent. Because hitinfo contains an reference to the actual listview cell object, it can be used direct if we share it between the two event handlers. No need to calculate the textbox position (C# code, details omitted):
    
    private ListViewHitTestInfo hitinfo;
    private TextBox editbox = new TextBox();
    
    public FormMain()
    {
        editbox.Parent = listView;
        editbox.Hide();
        editbox.LostFocus += new EventHandler(editbox_LostFocus);
        listView.MouseDoubleClick += new MouseEventHandler(listView_MouseDoubleClick);
        listView.FullRowSelect = true;
    }
    
    private void listView_MouseDoubleClick(object sender, MouseEventArgs e)
    {
        hitinfo = listView.HitTest(e.X, e.Y);
        editbox.Bounds = hitinfo.SubItem.Bounds;
        editbox.Text = hitinfo.SubItem.Text;
        editbox.Focus();
        editbox.Show();
    }
    
    void editbox_LostFocus(object sender, EventArgs e)
    {
        hitinfo.SubItem.Text = editbox.Text;
        editbox.Hide();
    }
    
    // Anders LC6vgren

    • on click editable listview rows and cells

      Posted by vahnar on 02/19/2013 06:41am

      thanks a lot after 10 days i successed through yor guide hope your more happy & success in ever

      Reply
    • ListViewSubItemsEdit

      Posted by Adnan on 01/20/2013 03:52am

      HI andlov, Thanks a lot. Finally, I got the proper solution from u..

      Reply
    • RE: Edit ListView SubItems

      Posted by Taggic on 10/30/2009 03:10am

      Hi Anders, sorry for my long absence here and very late reply. Possibly I've some time between xmas and new years day to update the posted code by your improvements. Thanks, Taggic

      Reply
    Reply
  • What is Globeseo.net?

    Posted by lihuidaizi on 07/19/2009 04:30am

    Thanks for sharing! www.globeseo.net, teach you how to earn money on the Internet!

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Learn How A Global Entertainment Company Saw a 448% ROI Every business today uses software to manage systems, deliver products, and empower employees to do their jobs. But software inevitably breaks, and when it does, businesses lose money -- in the form of dissatisfied customers, missed SLAs or lost productivity. PagerDuty, an operations performance platform, solves this problem by helping operations engineers and developers more effectively manage and resolve incidents across a company's global operations. …

  • Live Event Date: December 18, 2014 @ 2:00 p.m. ET / 11:00 a.m. PT The Internet of Things (IoT) incorporates physical devices into business processes using predictive analytics. While it relies heavily on existing Internet technologies, it differs by including physical devices, specialized protocols, physical analytics, and a unique partner network. To capture the real business value of IoT, the industry must move beyond customized projects to general patterns and platforms. Check out this upcoming webcast …

Most Popular Programming Stories

More for Developers

RSS Feeds