Monday, August 13, 2007

Using a ListView in VB.NET

Here is a basic example of how to use the Detail View with a ListView in VB.NET.
See also AutoFitListView and CopyListViewToClipboard.

Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load

' Set ListView Properties
ListView1.View = View.Details
ListView1.GridLines = True
ListView1.FullRowSelect = True
ListView1.HideSelection = False
ListView1.MultiSelect = False

' Create Columns Headers
ListView1.Columns.Add("Column A")
ListView1.Columns.Add("Column B")
ListView1.Columns.Add("Column C")

Dim tempValue As Integer = 0

For i As Integer = 0 To 9

' Create List View Item (Row)
Dim lvi As New ListViewItem

' First Column can be the listview item's Text
lvi.Text = "Row " + i.ToString

' Second Column is the first sub item
tempValue = tempValue + 1
lvi.SubItems.Add(tempValue.ToString)

' Third Column is the second sub item
tempValue = tempValue + 1
lvi.SubItems.Add(tempValue.ToString)

' Add the ListViewItem to the ListView
ListView1.Items.Add(lvi)

Next

End Sub

Private Sub ListView1_SelectedIndexChanged(ByVal sender As _
System.Object, ByVal e As System.EventArgs) _
Handles ListView1.SelectedIndexChanged

If ListView1.SelectedIndices.Count = 0 Then Return

Dim lvi As ListViewItem = _
ListView1.SelectedItems(0)

MessageBox.Show(lvi.Text + " has been selected.")

End Sub

9 comments:

  1. hmm..i can see i am the first one posting a comm abt this tutorial...
    i must say that this tutorial is really interesting and has helped me a lot in my final year project.
    thanks...
    hope to get more tutorial on vb.net on this site
    cia

    ReplyDelete
  2. very handy info. Thanks a lot
    cheers

    ReplyDelete
  3. Thanks, helped me get my head around this... nice work

    ReplyDelete
  4. Thanks. After much searching, this is the first example that didn't lose me in discussing databases and icons.

    ReplyDelete
  5. thanks ur info.....

    ReplyDelete
  6. Thank you. This was very helpful.

    I love that you use your blog as a reference on your own digital shelf - lol What a great idea! How much time have I wasted searching through old projects looking for code when I could have it at my fingertips? And it gives back to the community too. Cool!

    ReplyDelete
  7. Thanks. I have found the blog to very useful for finding my own stuff, and my posts show up on Google with everyone else's, so I don't even have to go to the blog to look things up.

    ReplyDelete
  8. can i add check box for list view???

    ReplyDelete

Note: Only a member of this blog may post a comment.