Created On:  05 July 2012


How can I retrieve the individual columns of data that are selected in a ListView control in a Visual COBOL Windows Forms application?


The following is an example which populates a 3 column listview with data and then sets the 2nd row to be the selected row and then when a button is clicked it will extract the columns from the first selected row into appropriate data items which in this simple case are strings.

class-id testlistview.Form1 is partial
   inherits type System.Windows.Forms.Form.
working-storage section.
method-id NEW.
01 row type ListViewItem.
procedure division.

    invoke self::InitializeComponent
    set row to new ListViewItem("R1Column1 Data")
    invoke row::SubItems::Add("R1Column2 Data")
    invoke row::SubItems::Add("R1Column3 Data")
    invoke listView1::Items::Add(row)

    set row to new ListViewItem("R2Column1 Data")
    invoke row::SubItems::Add("R2Column2 Data")
    invoke row::SubItems::Add("R2Column3 Data")
    invoke listView1::Items::Add(row)

    set row to new ListViewItem("R3Column1 Data")
    invoke row::SubItems::Add("R3Column2 Data")
    invoke row::SubItems::Add("R3Column3 Data")
    invoke listView1::Items::Add(row)
*> sets second row in listview to be selected row as indexes are 0 based.
    set listView1::Items[1]::Selected to true
end method.

method-id button1_Click final private.
01 row type ListViewItem.
01 column1 string.
01 column2 string.
01 column3 string.
procedure division using by value sender as object e as type System.EventArgs.

*> You can set the columns directly using the SubItems property of the SelectedItems property.
*> There can be multiple selected items so [0] gets the first one.

    set column1 to listView1::SelectedItems[0]::SubItems[0]
    set column2 to listView1::SelectedItems[0]::SubItems[1]
    set column3 to listView1::SelectedItems[0]::SubItems[2]

*> Or you can do the following which gets the selected Row from the SelectedItems property and then gets the column from it.

    set row to listView1::SelectedItems[0]
    set column2 to row::SubItems[1]
    set column3 to row::SubItems[2]

end method.
end class.