Listview first column empty

tqmd1

Well-known member
Joined
Dec 5, 2009
Messages
60
Programming Experience
Beginner
Dear Experts

I have following codes to to show data in listview.
It displays first column empty.
The value of first column is displayed in column2.
How to show value of first database field in column1

Please help

Dim StudentID As Integer
Dim Name As String
Dim Address As String
Dim Course As String

Dim row As DataRow

Dim item As ListViewItem
Dim str As String
Dim dt As DataTable

ListView1.View = View.Details
ListView1.Columns.Add("S #", 60, HorizontalAlignment.Center)
ListView1.Columns.Add("Name", 120, HorizontalAlignment.Left)
ListView1.Columns.Add("City", 120, HorizontalAlignment.Left)
ListView1.Columns.Add("Contact", 80, HorizontalAlignment.Left)

Str = "select * from employees"
dt = GetTable(Str)

For Each row In dt.Rows()

StudentID = row("sno")
Name = row("Name")
Address = row("city")
Course = row("phone")

item = New ListViewItem

item.SubItems.Add(StudentID)
item.SubItems.Add(Name)
item.SubItems.Add(Address)
item.SubItems.Add(Course)

ListView1.Items.Add(item)

Next
Me.ListView1.Focus()
Me.ListView1.Items(0).Selected = True

' this function is in main module
Public Function GetTable(ByVal mstr As String)
cmd = New SqlClient.SqlCommand(mstr, con)
da = New SqlClient.SqlDataAdapter(cmd)
dt = New DataTable
da.Fill(dt)
Return (dt)
End Function
 
First column is the ListViewItem Text, this is also same as SubItems(0) which is added automatically. When you do SubItems.Add you're adding from index 1 and up. Thus there are possibilities:

  • Set the item Text property:
    VB.NET:
    Dim lvi As New ListViewItem
    lvi.Text = "col1"
    ListView1.Items.Add(lvi)
  • Set Text of first SubItem:
    VB.NET:
    Dim lvi As New ListViewItem
    lvi.SubItems(0).Text = "col1"
    ListView1.Items.Add(lvi)
  • Use the item constructor:
    VB.NET:
    Dim lvi As New ListViewItem("col1")
    ListView1.Items.Add(lvi)
  • Use the Items collection Add method:
    VB.NET:
    Dim lvi As ListViewItem = Me.ListView1.Items.Add("col1")
The latter is easiest since it creates the ListViewItem, sets the Text, and add it to the ListView in one operation. The reference to the item created is returned from the Add function, so you can continue adding subitems to that.
 
{Be hAppy}

Replace Following 5 Lines

==========
item = New ListViewItem

item.SubItems.Add(StudentID)
item.SubItems.Add(Name)
item.SubItems.Add(Address)
item.SubItems.Add(Course)
==========

As following 4 lines

==========

item = New ListViewItem(StudentID.ToString)
item.SubItems.Add(Name)
item.SubItems.Add(Address)
item.SubItems.Add(Course)
==========
 
Back
Top