Library tutorials & articles

ListView Control

Sorting Items

To make the list view sort its items when the user clicks on a column header, use this code in the ListView_ColumnClick event.

With ListView1 '// change to the name of the list view
    Static iLast As Integer, iCur As Integer
    .Sorted = True
    iCur = ColumnHeader.Index - 1
    If iCur = iLast Then .SortOrder = IIf(.SortOrder = 1, 0, 1)
    .SortKey = iCur
    iLast = iCur
End With


Simple!

Comments

  1. 14 Nov 2007 at 22:00

    How to sort a ListView control? Here is the code I have written to handle just that. This code also includes a context menu of items I found I needed on almost every ListView I used (I use them alot).

    Can either create a file with this in it and add it to any project you need it in, or you can create a Class Library and add this code, compile it and add a reference to any project you wish to use this code in.

    How to use the ListViewSorter:

    In your ListView's ColumnClick event, place this line of code:

        ... 

        SortListViewColumn(sender, e)

         ...

     

    How to use the context menu:

    In your form's Load event, add the following code.

        ...

        Dim objListViewMenu As New clsListViewMenu(True)

        ListView1.ContextMenuStrip = objListViewMenu.ListViewMenu

         ...
     

    Or, if you have a Context Menu you need for the list view, you can merge them with this line of code:

        ... 

        ListView1.ContextMenuStrip = objListViewMenu.Merge(YOURCONTEXTMENU)

         ...

    There are various properties associated with the ListViewMenu object, all should be pretty self-evident.

    Enjoy...

     

     

    Imports System
    Imports System.Windows.Forms
    Imports System.ComponentModel
    Imports System.Drawing

    Namespace ListViewManipulation

      Public Module ListViewSorter

        Public Enum SortOrders
          Ascending = 0
          Descending
        End Enum

        Private Sub ErrorMessage(ByVal Text As String)
          MsgBox(Text, MsgBoxStyle.Exclamation, "YOUR TITLE HERE")
        End Sub

        Public Sub AutoSizeColumns(ByVal ListView As ListView, Optional ByVal EvenSpacing As Boolean = False)

          Dim intColumns As Integer = ListView.Columns.Count
          Dim intClientWidth As Integer = ListView.ClientRectangle.Width
          Dim intWidths(intColumns) As Integer
          Dim intWidth As Integer = 0

          With ListView
            .BeginUpdate()

            Try
              If EvenSpacing Then
                intWidth = CInt((intClientWidth) / intColumns)

                For Each objColumn As ColumnHeader In .Columns
                  objColumn.Width = intWidth
                Next

                If (intWidth * (intColumns)) > intClientWidth Then
                  Dim C As ColumnHeader = .Columns(intColumns - 1)
                  C.Width -= (intWidth * intColumns) - intClientWidth
                End If
              Else
                .AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent)
                For Each C As ColumnHeader In .Columns
                  intWidths(C.Index) = C.Width
                Next

                .AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize)
                For Each C As ColumnHeader In .Columns
                  If C.Width < intWidths(C.Index) Then C.Width = intWidths(C.Index)
                Next
              End If
            Catch ex As Exception
              ErrorMessage(ex.Message)
            End Try

            .EndUpdate()
          End With

        End Sub

        Private Function SmallerOf(ByVal value1 As Integer, ByVal value2 As Integer) As Integer

          Dim intReturn As Integer = 0

          If value1 <= value2 Then
            intReturn = value1
          Else
            intReturn = value2
          End If

          Return intReturn

        End Function

        Public Sub SortListViewColumn(ByVal sender As Object, ByVal e As System.Windows.Forms.ColumnClickEventArgs)

          Try
            If sender Is Nothing Then Throw New NullReferenceException("[sender] is null.")
            If e Is Nothing Then Throw New NullReferenceException("[ColumnClickEventArgs] is null.")
            If sender.GetType IsNot GetType(ListView) Then Throw New Exception("[sender] must be a ListView control.")

            Static objHistory As New Dictionary(Of Integer, clsClickHistory)

            Dim objLast As clsClickHistory = Nothing
            Dim intHash As Integer = sender.GetHashCode

            If Not objHistory.ContainsKey(intHash) Then
              objHistory.Add(intHash, New clsClickHistory(e.Column, SortOrders.Ascending))
            End If

            objLast = objHistory(intHash)

            With objLast
              If .Column = e.Column Then
                .Order = .FlipOrder
              Else
                .Order = SortOrders.Descending
              End If

              .Column = e.Column
            End With

            With DirectCast(sender, ListView)
              .BeginUpdate()
              .ListViewItemSorter = New clsListViewSorter(objLast.Column, objLast.Order)
              .ListViewItemSorter = Nothing
              .EndUpdate()
            End With
          Catch ex As Exception
            ErrorMessage(ex.Message)
            With DirectCast(sender, ListView)
              .ListViewItemSorter = Nothing
              .EndUpdate()
            End With
          End Try

        End Sub

        Private Class clsListViewSorter
          Implements IComparer

          Private intColumn As Integer = 0
          Private intOrder As SortOrders = SortOrders.Ascending

          Public Sub New()

          End Sub

          Public Sub New(ByVal Column As Integer, ByVal SortOrder As SortOrders)
            Me.Column = Column
            Me.Order = SortOrder
          End Sub

          Public Property Order() As SortOrders
            Get
              Return intOrder
            End Get
            Set(ByVal value As SortOrders)
              If Not System.Enum.IsDefined(GetType(SortOrders), value) Then Throw New Exception("Value is not defined in Enum " & GetType(SortOrder).Name)
              intOrder = value
            End Set
          End Property

          Public Property Column() As Integer
            Get
              Return intColumn
            End Get
            Set(ByVal value As Integer)
              intColumn = value
            End Set
          End Property

          Private Function IsNumeric(ByVal Chars() As Char) As Boolean

            Dim bolPointSeen As Boolean = False

            For Each c As Char In Chars
              If Not Char.IsNumber(c) Then
                If c = "."c Then
                  If bolPointSeen Then Return False
                  bolPointSeen = True
                Else
                  Return False
                End If
              End If
            Next

            Return True

          End Function

          Public Function Compare(ByVal Item1 As Object, ByVal Item2 As Object) As Integer _
           Implements IComparer.Compare

            Dim chr1() As Char = DirectCast(Item1, ListViewItem).SubItems(intColumn).Text.ToCharArray
            Dim chr2() As Char = DirectCast(Item2, ListViewItem).SubItems(intColumn).Text.ToCharArray

            If chr1 = chr2 Then Return 0

            If IsNumeric(chr1) Then
              If IsNumeric(chr2) Then
                If intOrder = SortOrder.Ascending Then
                  Return Val(chr1).CompareTo(Val(chr2))
                Else
                  Return Val(chr2).CompareTo(Val(chr1))
                End If
              End If
            End If

            For i As Integer = 0 To SmallerOf(chr1.GetUpperBound(0), chr2.GetUpperBound(0))
              If chr1(i) <> chr2(i) Then
                If intOrder = SortOrder.Ascending Then
                  Return String.Compare(chr1(i), chr2(i))
                Else
                  Return String.Compare(chr2(i), chr1(i))
                End If
              End If
            Next

          End Function
        End Class

        Private Class clsClickHistory
          Dim intColumn As Integer = 0
          Dim intOrder As SortOrders = SortOrders.Ascending

          Public Sub New()

          End Sub

          Public Sub New(ByVal Column As Integer, ByVal Order As SortOrders)
            Me.Column = Column
            Me.Order = Order
          End Sub

          Public Property Column() As Integer
            Get
              Return intColumn
            End Get
            Set(ByVal value As Integer)
              intColumn = value
            End Set
          End Property

          Public Property Order() As SortOrders
            Get
              Return intOrder
            End Get
            Set(ByVal value As SortOrders)
              If Not System.Enum.IsDefined(GetType(SortOrders), value) Then Throw New Exception("Value is not defined in Enum " & GetType(SortOrders).Name)
              intOrder = value
            End Set
          End Property

          Public Function FlipOrder() As SortOrders
            Return DirectCast(Math.Abs(CInt(intOrder) - 1), SortOrders)
          End Function
        End Class

      End Module

      Public Class ListViewMenuCancelEventArgs
        Inherits System.ComponentModel.CancelEventArgs

        Dim objLV As ListView = Nothing
        Dim objCE As CancelEventArgs = Nothing

        Public Sub New(ByVal ListView As ListView, ByVal e As CancelEventArgs)
          Me.ListView = ListView
          Me.CancelEventArgs = e
        End Sub

        Public Property ListView() As ListView
          Get
            Return objLV
          End Get
          Set(ByVal value As ListView)
            objLV = value
          End Set
        End Property

        Public Property CancelEventArgs() As CancelEventArgs
          Get
            Return objCE
          End Get
          Set(ByVal value As CancelEventArgs)
            objCE = value
          End Set
        End Property

      End Class

      Public Class clsListViewMenu

        Public Event ContextMenuOpening(ByVal sender As Object, ByVal e As ListViewMenuCancelEventArgs)

        Dim WithEvents mnuViewStyle As New ContextMenuStrip
        Dim WithEvents mnuViewView As ToolStripMenuItem = Nothing
        Dim WithEvents mnuViewSort As ToolStripMenuItem = Nothing
        Dim WithEvents mnuViewAutosize As ToolStripMenuItem = Nothing
        Dim WithEvents objLargeIcons As ToolStripMenuItem = Nothing
        Dim WithEvents objSmallIcons As ToolStripMenuItem = Nothing
        Dim WithEvents objTiles As ToolStripMenuItem = Nothing
        Dim WithEvents objList As ToolStripMenuItem = Nothing
        Dim WithEvents objDetails As ToolStripMenuItem = Nothing
        Dim WithEvents objGridlines As ToolStripMenuItem = Nothing
        Dim WithEvents objAutoSizeEven As ToolStripMenuItem = Nothing
        Dim WithEvents objAutoSizeFit As ToolStripMenuItem = Nothing

        Dim objSource As ListView = Nothing
        Dim bolAutosize As Boolean = False
        Dim bolHideViews As Boolean = False
        Dim bolHideResize As Boolean = False
        Dim bolHideGridlines As Boolean = False
        Dim bolHideSorting As Boolean = False

        Public Sub New(Optional ByVal AutoSizeColumnsOnViewChange As Boolean = False)
          Me.AutoResizeColumnsOnViewChange = AutoSizeColumnsOnViewChange
          LocalInitialize()
        End Sub

        Protected Overrides Sub Finalize()

          For Each I As ToolStripMenuItem In mnuViewSort.DropDownItems
            RemoveHandler I.Click, AddressOf ColumnSort_Click
          Next

          RemoveHandler DirectCast(mnuViewView.Owner, ContextMenuStrip).Opening, AddressOf mnuViewStyle_Opening

          MyBase.Finalize()

        End Sub

        Private Sub LocalInitialize()

          Dim strViews As String = Nothing
          Dim strSizing As String = Nothing
          Dim strSorting As String = Nothing
          Dim strGrids As String = Nothing
          Dim strEven As String = Nothing
          Dim strFit As String = Nothing
          Dim strLarge As String = Nothing
          Dim strSmall As String = Nothing
          Dim strTiles As String = Nothing
          Dim strList As String = Nothing
          Dim strDetails As String = Nothing

          strViews = "View"
          strSizing = "Resize headers"
          strSorting = "Sort by"
          strGrids = "Show gridlines"
          strEven = "Evenly"
          strFit = "To contents"
          strLarge = "Large icons"
          strSmall = "Small icons"
          strTiles = "Tiles"
          strList = "List"
          strDetails = "Details"

          With mnuViewStyle.Items
            mnuViewView = DirectCast(.Add(strViews), ToolStripMenuItem)
            mnuViewAutosize = DirectCast(.Add(strSizing), ToolStripMenuItem)
            mnuViewSort = DirectCast(.Add(strSorting), ToolStripMenuItem)
            objGridlines = DirectCast(.Add(strGrids), ToolStripMenuItem)
          End With

          With mnuViewAutosize.DropDownItems
            objAutoSizeEven = DirectCast(.Add(strEven), ToolStripMenuItem)
            objAutoSizeFit = DirectCast(.Add(strFit), ToolStripMenuItem)
          End With

          With mnuViewView.DropDownItems
            objLargeIcons = DirectCast(.Add(strLarge), ToolStripMenuItem)
            objSmallIcons = DirectCast(.Add(strSmall), ToolStripMenuItem)
            objTiles = DirectCast(.Add(strTiles), ToolStripMenuItem)
            objList = DirectCast(.Add(strList), ToolStripMenuItem)
            objDetails = DirectCast(.Add(strDetails), ToolStripMenuItem)
          End With

          objLargeIcons.Tag = View.LargeIcon
          objSmallIcons.Tag = View.SmallIcon
          objTiles.Tag = View.Tile
          objList.Tag = View.List
          objDetails.Tag = View.Details

        End Sub

    #Region "Properties"
        Public ReadOnly Property ListViewMenu() As ContextMenuStrip
          Get
            Return mnuViewStyle
          End Get
        End Property

        Public Property AutoResizeColumnsOnViewChange() As Boolean
          Get
            Return bolAutosize
          End Get
          Set(ByVal value As Boolean)
            bolAutosize = value
          End Set
        End Property

        Public Property HideViewOptions() As Boolean
          Get
            Return bolHideViews
          End Get
          Set(ByVal value As Boolean)
            bolHideViews = value
          End Set
        End Property

        Public Property HideResizeOptions() As Boolean
          Get
            Return bolHideResize
          End Get
          Set(ByVal value As Boolean)
            bolHideResize = value
          End Set
        End Property

        Public Property HideGridlinesOption() As Boolean
          Get
            Return bolHideGridlines
          End Get
          Set(ByVal value As Boolean)
            bolHideGridlines = value
          End Set
        End Property

        Public Property HideSortingOption() As Boolean
          Get
            Return bolHideSorting
          End Get
          Set(ByVal value As Boolean)
            bolHideSorting = value
          End Set
        End Property

        Public Property DisableViewOptions() As Boolean
          Get
            Return Not mnuViewView.Enabled
          End Get
          Set(ByVal value As Boolean)
            mnuViewView.Enabled = Not value
          End Set
        End Property

        Public Property DisableViewLargeIcons() As Boolean
          Get
            Return Not objLargeIcons.Enabled
          End Get
          Set(ByVal value As Boolean)
            objLargeIcons.Enabled = Not value
          End Set
        End Property

        Public Property DisableViewSmallIcons() As Boolean
          Get
            Return Not objSmallIcons.Enabled
          End Get
          Set(ByVal value As Boolean)
            objSmallIcons.Enabled = Not value
          End Set
        End Property

        Public Property DisableViewList() As Boolean
          Get
            Return Not objList.Enabled
          End Get
          Set(ByVal value As Boolean)
            objList.Enabled = Not value
          End Set
        End Property

        Public Property DisableViewTiles() As Boolean
          Get
            Return Not objTiles.Enabled
          End Get
          Set(ByVal value As Boolean)
            objTiles.Enabled = Not value
          End Set
        End Property

        Public Property DisableViewDetails() As Boolean
          Get
            Return Not objDetails.Enabled
          End Get
          Set(ByVal value As Boolean)
            objDetails.Enabled = Not value
          End Set
        End Property

        Public Property DisableResizingOptions() As Boolean
          Get
            Return DisableResizeEven And DisableResizeFit
          End Get
          Set(ByVal value As Boolean)
            DisableResizeEven = value
            DisableResizeFit = value
          End Set
        End Property

        Public Property DisableResizeFit() As Boolean
          Get
            Return Not objAutoSizeFit.Enabled
          End Get
          Set(ByVal value As Boolean)
            objAutoSizeFit.Enabled = Not value
          End Set
        End Property

        Public Property DisableResizeEven() As Boolean
          Get
            Return Not objAutoSizeEven.Enabled
          End Get
          Set(ByVal value As Boolean)
            objAutoSizeEven.Enabled = Not value
          End Set
        End Property

        Public Property DisbableGridlinesOption() As Boolean
          Get
            Return Not objGridlines.Enabled
          End Get
          Set(ByVal value As Boolean)
            objGridlines.Enabled = Not value
          End Set
        End Property

        Public Property DisableSortingOption() As Boolean
          Get
            Return Not mnuViewSort.Enabled
          End Get
          Set(ByVal value As Boolean)
            mnuViewSort.Enabled = Not value
          End Set
        End Property
    #End Region

        Private Sub MenuItem_Click(ByVal sender As Object, ByVal e As System.EventArgs) _
        Handles objDetails.Click, objLargeIcons.Click, objList.Click, _
                objSmallIcons.Click, objTiles.Click

          Dim objListView As ListView = objSource
          Dim objMenu As ToolStripMenuItem = CType(sender, ToolStripMenuItem)
          Dim intView As View = DirectCast(CInt(objMenu.Tag), View)

          If objListView.View <> intView Then
            objListView.View = intView
            If bolAutosize And (objListView.View = View.Details) Then AutoSizeColumns(objListView)
          End If

        End Sub

        Private Sub objGridlines_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles objGridlines.Click
          objGridlines.Checked = Not objGridlines.Checked
          objSource.GridLines = objGridlines.Checked
        End Sub

        Private Sub AutoSizeEven_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles objAutoSizeEven.Click
          AutoSizeColumns(objSource, True)
        End Sub

        Private Sub AutoSizeFit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles objAutoSizeFit.Click
          AutoSizeColumns(objSource, False)
        End Sub

        Public Function Merge(ByVal Parent As ContextMenuStrip, Optional ByVal ParentItemsOnTop As Boolean = False) As ContextMenuStrip

          Dim objItems() As ToolStripItem = Nothing
          Dim objParentItems() As ToolStripItem = Nothing
          Dim bolAddingSeperator As Boolean = Parent.Items.Count > 0

          Array.Resize(objItems, mnuViewStyle.Items.Count)
          Array.Resize(objParentItems, Parent.Items.Count)

          mnuViewStyle.Items.CopyTo(objItems, 0)
          Parent.Items.CopyTo(objParentItems, 0)

          If ParentItemsOnTop Then
            Parent.Items.AddRange(objParentItems)
            If bolAddingSeperator Then Parent.Items.Add(New ToolStripSeparator)
            Parent.Items.AddRange(objItems)
          Else
            Parent.Items.AddRange(objItems)
            If bolAddingSeperator Then Parent.Items.Add(New ToolStripSeparator)
            Parent.Items.AddRange(objParentItems)
          End If

          AddHandler Parent.Opening, AddressOf mnuViewStyle_Opening

          Return Parent

        End Function

        Private Sub mnuViewStyle_Opening(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles mnuViewStyle.Opening

          Dim objMenu As ContextMenuStrip = Nothing
          Dim intStyle As View = View.Details

          If sender.GetType IsNot GetType(ContextMenuStrip) Then Throw New Exception("Sender must be a ContextMenuStrip.")

          objMenu = DirectCast(sender, ContextMenuStrip)

          If objMenu.SourceControl.GetType IsNot GetType(ListView) Then Throw New Exception("SourceControl is not a ListView.")

          objSource = DirectCast(objMenu.SourceControl, ListView)
          intStyle = objSource.View

          objLargeIcons.Checked = False
          objSmallIcons.Checked = False
          objTiles.Checked = False
          objList.Checked = False
          objDetails.Checked = False

          Select Case intStyle
            Case View.Details
              objDetails.Checked = True
            Case View.LargeIcon
              objLargeIcons.Checked = True
            Case View.List
              objList.Checked = True
            Case View.SmallIcon
              objSmallIcons.Checked = True
            Case View.Tile
              objTiles.Checked = True
          End Select

          objGridlines.Checked = objSource.GridLines
          mnuViewView.Visible = Not bolHideViews
          mnuViewAutosize.Visible = objSource.View = View.Details And Not bolHideResize
          mnuViewSort.Visible = objSource.View = View.Details And Not bolHideSorting
          objGridlines.Visible = objSource.View = View.Details And Not bolHideGridlines

          Dim objItem As ToolStripMenuItem = Nothing

          For Each I As ToolStripMenuItem In mnuViewSort.DropDownItems
            RemoveHandler I.Click, AddressOf ColumnSort_Click
          Next

          mnuViewSort.DropDownItems.Clear()

          For Each H As ColumnHeader In objSource.Columns
            With mnuViewSort.DropDownItems
              objItem = DirectCast(.Add(H.Text), ToolStripMenuItem)
              With objItem
                If .Text.Trim = "" Then .Text = "[" & .Text & "]"
                .Tag = H
              End With

              AddHandler objItem.Click, AddressOf ColumnSort_Click
            End With
          Next

          RaiseEvent ContextMenuOpening(sender, New ListViewMenuCancelEventArgs(objSource, e))

        End Sub

        Private Sub ColumnSort_Click(ByVal sender As Object, ByVal e As EventArgs)
          Dim H As ColumnHeader = DirectCast(DirectCast(sender, ToolStripMenuItem).Tag, ColumnHeader)
          SortListViewColumn(objSource, New ColumnClickEventArgs(H.Index))
        End Sub
      End Class

    End Namespace

  2. 14 Nov 2007 at 21:44

    [quote user="Maxjonz"]

    I found that the following code didn't work for me

    ListView1.ListItems.Remove(ListView1.SelectedItem) '// removes the selected item

    I had to use

    ListView1.ListItems.Remove(ListView1.SelectedItem.Index) 

    Also  - it wasn't obvious to me to start with  ( I'm a newbie to listviews )

    but to  'get at' the data in the views one had to use

    ListView1.ListItems.Item(x)    where  x is a valid number in the  range 1 to ListView1.ListItems.Count  (NOT   0 to .Count - 1 as in normal Visual Basic)

     Cheers

    Maxjonz

    [/quote] 

     

    ListView1.SelectedItems(0).Remove()

    Or to remove all selected items:

    For Each I as ListViewItem In ListView1.SelectedItems

        I.Remove() 

    Next 

     

  3. 10 Aug 2007 at 04:34

    Hey everyone here are some example of Database that use ListView:

    if u need in C# pls copy this code convert to C# your self.

    1. Use Microsoft Access Database
    • Module1 code

    Imports

    System.Data.OleDb

    Imports

    System.IO

    Module

    Module1

    Dim cnn As New OleDb.OleDbConnection

    Public LocPos As Integer

    Public TotalPos As Integer

    Sub DBConnection(ByVal PTH As String)

    Try

    cnn =

    New OleDbConnection("Provider=microsoft.jet.oledb.4.0; data source='" & PTH & "'")

    cnn.Open()

    Catch ex As Exception

    MsgBox(ex.Message, MsgBoxStyle.Information,

    "")

    End

    End Try

    End Sub

    Public Enum CustomDel

    DellAll = 1

    DelCustom = 2

    End Enum

    Public Enum CtrlDorE

    CtrlDiabled = 1

    CtrlEnabled = 2

    End Enum

    Public Enum Optionshow

    SHowAllFields = 1

    SHowSomeField = 2

    End Enum

    Sub DeleteData(ByVal tbl As String, ByVal FieldCon As String, ByVal ValueCon As String, ByVal Deloption As CustomDel)

    Try

    Dim cm As New OleDb.OleDbCommand

    Dim del As Integer

    Dim SQLa As String : Dim SQLc As String

    SQLa =

    "delete * from " & tbl

    SQLc =

    "delete from " & tbl & " where " & FieldCon & "='" & ValueCon & "'"

    Select Case Deloption

    Case 1 : del = CustomDel.DellAll : cm.CommandText = SQLa

    Case 2 : del = CustomDel.DelCustom : cm.CommandText = SQLc

    End Select

    cm.Connection = cnn

    cm.ExecuteNonQuery()

    Catch ex As Exception

    MsgBox(ex.Message)

    End Try

    End Sub

    Sub TransferData2txt(ByVal frm As Form, ByVal tbl As String, ByVal Pos As Integer, ByVal ParamArray Txt() As String)

    Dim cm As New OleDb.OleDbCommand

    Dim ds As New DataSet

    Dim adp As New OleDbDataAdapter

    Dim ct As Control : Dim i As Integer

    On Error GoTo err

    cm.CommandText =

    "select * from " & tbl

    cm.Connection = cnn

    adp =

    New OleDbDataAdapter("select * from " & tbl, cnn)

    ds =

    New DataSet(tbl)

    adp.Fill(ds, tbl)

    TotalPos = ds.Tables(tbl).Rows.Count - 1

    adp.Dispose()

    Dim dr As OleDbDataReader = cm.ExecuteReader

    If ds Is Nothing Then Return

    With ds.Tables(tbl).Rows(Pos)

    For Each ct In frm.Controls

    If TypeOf ct Is TextBox Then

    For i = 0 To UBound(Txt)

    If LCase(Txt(i)) = LCase(ct.Name) Then

    ct.Text = .Item(i).ToString

    i = i + 1 :

    Exit For

    End If

    Next

    End If

    Next

    End With

    dr.Close()

    err:

    Exit Sub

    End Sub

    Function IDcreator(ByVal tbl As String, ByVal IDStyle As String, ByVal Connector As String, ByVal FormatNumber As String, ByVal Field As String) As String

    Dim cm As New OleDb.OleDbCommand()

    Dim da As New OleDb.OleDbDataAdapter()

    Dim ds As New DataSet()

    Dim Tem As String

    Try

    ds =

    New DataSet(tbl)

    da =

    New OleDb.OleDbDataAdapter("select * from " & tbl, cnn)

    da.Fill(ds, tbl)

    Dim RecordCount = ds.Tables(tbl).Rows.Count() 'count all records in one table

    Tem = IDStyle & Connector & Format(RecordCount + 1, FormatNumber)

    Dim i = 1

    Do

    i = i + 1

    cm.CommandText =

    "select * from " & tbl & " where " & Field & " = '" & Tem & "'"

    cm.Connection = cnn

    Dim rst As OleDb.OleDbDataReader = cm.ExecuteReader

    If rst.HasRows Then

    Tem = IDStyle & Connector & Format(RecordCount + i, FormatNumber)

    rst.Close()

    Else : IDcreator = Tem : Exit Function

    End If

    Loop

    Catch ex As Exception

    MsgBox(ex.Message)

    End Try

    End Function

    Sub showDataTolst(ByVal tbl As String, ByVal lst As ListView, ByVal showOption As Optionshow, ByVal ParamArray SelectField() As String)

    Dim cm As New OleDb.OleDbCommand()

    Dim da As New OleDb.OleDbDataAdapter()

    Dim ds As New DataSet()

    Dim Opt As Integer, TemField As String

    Dim a As Integer, Sql As String, i%, ii%

    Dim ColH As ColumnHeader

    lst.View = View.Details

    lst.Clear()

    Select Case showOption

    Case 1 : Opt = Optionshow.SHowAllFields

    Sql =

    "select * from " & tbl

    Case 2 : Opt = Optionshow.SHowSomeField

    For a = 0 To UBound(SelectField)

    TemField = TemField & SelectField(a) &

    ","

    Next

    TemField = Strings.Left(TemField, Len(TemField) - 1)

    Sql =

    "select " & TemField & " from " & tbl

    End Select

    cm.CommandText = Sql

    cm.Connection = cnn

    da =

    New OleDb.OleDbDataAdapter(Sql, cnn)

    ds =

    New DataSet(tbl)

    da.Fill(ds, tbl)

    For i = 0 To ds.Tables(tbl).Columns.Count - 1

    Dim fieldName = ds.Tables(tbl).Columns(i).ColumnName ' find caption of field name

    ColH =

    New ColumnHeader()

    ColH.Text = fieldName

    lst.Columns.Add(ColH)

    Next

    For Each ColH In lst.Columns

    ColH.Width = 90

    Next

    Dim dr As OleDbDataReader = cm.ExecuteReader

    While dr.Read

    Dim lstitem As ListViewItem

    For i = 0 To dr.FieldCount - 1

    lstitem =

    New ListViewItem(dr.Item(i).ToString)

    For ii = 1 To dr.FieldCount - 1

    lstitem.SubItems.Add(dr.Item(ii).ToString)

    Next

    lst.Items.Add(lstitem)

    Exit For

    Next

    End While

    dr.Close()

    End Sub

    Sub AddNewRecord(ByVal tbl As String, ByVal ParamArray Data() As String)

    Dim cm As New OleDb.OleDbCommand()

    Dim da As New OleDb.OleDbDataAdapter()

    Dim ds As New DataSet()

    Dim Temp As String

    Dim FTemp As String

    Try

    ds =

    New DataSet(tbl)

    da =

    New OleDb.OleDbDataAdapter("select * from " & tbl, cnn)

    da.Fill(ds, tbl)

    Dim i As Integer

    For i = 0 To UBound(Data)

    Dim fieldName = ds.Tables(tbl).Columns(i).ColumnName ' find caption of field name

    Temp = Temp & fieldName &

    ","

    FTemp = FTemp &

    "'" & Data(i) & "'" & ","

    Next

    Temp = Strings.Left(Temp, Len(Temp) - 1)

    FTemp = Strings.Left(FTemp, Len(FTemp) - 1)

    Dim sql As String

    sql =

    "Insert into " & tbl & "(" & Temp & ")" & " Values(" & FTemp & ")"

    cm.CommandText = sql

    cm.Connection = cnn

    cm.ExecuteNonQuery()

    Catch ex As Exception

    MsgBox(ex.Message)

    End Try

    End Sub

    Sub UpDateDataToTable(ByVal tbl As String, ByVal FieldCon As String, ByVal ValueCon As String, ByVal ParamArray Data() As String)

    Try

    Dim Temp As String

    Dim cm As New OleDb.OleDbCommand

    Dim da As New OleDb.OleDbDataAdapter()

    Dim ds As New DataSet()

    ds =

    New DataSet(tbl)

    da =

    New OleDb.OleDbDataAdapter("select * from " & tbl, cnn)

    da.Fill(ds, tbl)

    Dim i As Integer

    For i = 0 To UBound(Data)

    Dim fieldName = ds.Tables(tbl).Columns(i).ColumnName ' find caption of field name

    Temp = Temp & fieldName &

    "='" & Data(i) & "',"

    Next

    Temp = Strings.Left(Temp, Len(Temp) - 1)

    cm.CommandText =

    "update " & tbl & " set " & Temp & " where " & FieldCon & "='" & ValueCon & "'"

    cm.Connection = cnn

    cm.ExecuteNonQuery()

    Catch ex As Exception

    MsgBox(ex.Message)

    End Try

    End Sub

    End

    Module
    1. Use SqlServer

    connect direct to SqlSever (MS SQL Server Studio 2005)

    Imports System.Data.SqlClient
    Dim Cnn As New SqlConnection
    Dim CnnStr$
    CnnStr = "Data Source=PC2\SQLEXPRESS;Initial Catalog=KhmerDictionary;Integrated Security=True;Pooling=False;"
    Cnn = New SqlConnection(CnnStr)
    Cnn.Open()

    Connect Indirect to Sql Server Database File

    Imports System.Data.SqlClient
    Dim Cnn As New SqlConnection
    Dim CnnStr$
    CnnStr="Data Source=.\SQLEXPRESS;AttachDbFilename="C:\NimolProject\Dictionary Testing\Original DBDictionary\KhmerDictionary.mdf";Integrated Security=True;Connect Timeout=30;User Instance=True"
    Cnn = New SqlConnection(CnnStr)
    Cnn.Open()















    • Modul2 for Sqlserver connection

    Imports

    System.Data.SqlClient

    Module

    Module2

    Dim cnn As New SqlClient.SqlConnection

    Public LocPos As Integer

    Public TotalPos As Integer

    Public Enum CustomDel

    DellAll = 1

    DelCustom = 2

    End Enum

    Public Enum Optionshow

    SHowAllFields = 1

    SHowSomeField = 2

    End Enum

    Sub DeleteData(ByVal tbl As String, ByVal FieldCon As String, ByVal ValueCon As String, ByVal Deloption As CustomDel)

    Try

    Dim cm As New SqlClient.SqlCommand

    Dim del As Integer

    Dim SQLa As String : Dim SQLc As String

    SQLa =

    "delete * from " & tbl

    SQLc =

    "delete from " & tbl & " where " & FieldCon & "='" & ValueCon & "'"

    Select Case Deloption

    Case 1 : del = CustomDel.DellAll : cm.CommandText = SQLa

    Case 2 : del = CustomDel.DelCustom : cm.CommandText = SQLc

    End Select

    cm.Connection = cnn

    cm.ExecuteNonQuery()

    Catch ex As Exception

    MsgBox(ex.Message)

    End Try

    End Sub

    Sub TransferData2txt(ByVal frm As Form, ByVal tbl As String, ByVal Pos As Integer, ByVal ParamArray Txt() As String)

    Dim cm As New SqlClient.SqlCommand

    Dim ds As New DataSet

    Dim adp As New SqlClient.SqlDataAdapter

    Dim ct As Control : Dim i As Integer

    On Error GoTo err

    cm.CommandText =

    "select * from " & tbl

    cm.Connection = cnn

    adp =

    New SqlClient.SqlDataAdapter("select * from " & tbl, cnn)

    ds =

    New DataSet(tbl)

    adp.Fill(ds, tbl)

    TotalPos = ds.Tables(tbl).Rows.Count - 1

    adp.Dispose()

    Dim dr As SqlClient.SqlDataReader = cm.ExecuteReader

    If ds Is Nothing Then Return

    With ds.Tables(tbl).Rows(Pos)

    For Each ct In frm.Controls

    If TypeOf ct Is TextBox Then

    For i = 0 To UBound(Txt)

    If LCase(Txt(i)) = LCase(ct.Name) Then

    ct.Text = .Item(i).ToString

    i = i + 1 :

    Exit For

    End If

    Next

    End If

    Next

    End With

    dr.Close()

    err:

    Exit Sub

    End Sub

    Function IDcreator(ByVal tbl As String, ByVal IDStyle As String, ByVal Connector As String, ByVal FormatNumber As String, ByVal Field As String) As String

    Dim cm As New SqlClient.SqlCommand

    Dim da As New SqlClient.SqlDataAdapter

    Dim ds As New DataSet()

    Dim Tem As String

    Try

    ds =

    New DataSet(tbl)

    da =

    New SqlClient.SqlDataAdapter("select * from " & tbl, cnn)

    da.Fill(ds, tbl)

    Dim RecordCount = ds.Tables(tbl).Rows.Count() 'count all records in one table

    Tem = IDStyle & Connector & Format(RecordCount + 1, FormatNumber)

    Dim i = 1

    Do

    i = i + 1

    cm.CommandText =

    "select * from " & tbl & " where " & Field & " = '" & Tem & "'"

    cm.Connection = cnn

    Dim rst As SqlClient.SqlDataReader = cm.ExecuteReader

    If rst.HasRows Then

    Tem = IDStyle & Connector & Format(RecordCount + i, FormatNumber)

    rst.Close()

    Else : IDcreator = Tem : Exit Function

    End If

    Loop

    Catch ex As Exception

    MsgBox(ex.Message)

    End Try

    End Function

    Sub showDataTolst(ByVal tbl As String, ByVal lst As ListView, ByVal showOption As Optionshow, ByVal ParamArray SelectField() As String)

    Dim cm As New SqlClient.SqlCommand

    Dim da As New SqlClient.SqlDataAdapter

    Dim ds As New DataSet()

    Dim Opt As Integer, TemField As String

    Dim a As Integer, Sql As String, i%, ii%

    Dim ColH As ColumnHeader

    lst.View = View.Details

    lst.Clear()

    Select Case showOption

    Case 1 : Opt = Optionshow.SHowAllFields

    Sql =

    "select * from " & tbl

    Case 2 : Opt = Optionshow.SHowSomeField

    For a = 0 To UBound(SelectField)

    TemField = TemField & SelectField(a) &

    ","

    Next

    TemField = Strings.Left(TemField, Len(TemField) - 1)

    Sql =

    "select " & TemField & " from " & tbl

    End Select

    cm.CommandText = Sql

    cm.Connection = cnn

    da =

    New SqlClient.SqlDataAdapter(Sql, cnn)

    ds =

    New DataSet(tbl)

    da.Fill(ds, tbl)

    For i = 0 To ds.Tables(tbl).Columns.Count - 1

    Dim fieldName = ds.Tables(tbl).Columns(i).ColumnName ' find caption of field name

    ColH =

    New ColumnHeader()

    ColH.Text = fieldName

    lst.Columns.Add(ColH)

    Next

    For Each ColH In lst.Columns

    ColH.Width = 90

    Next

    Dim dr As SqlClient.SqlDataReader = cm.ExecuteReader

    While dr.Read

    Dim lstitem As ListViewItem

    For i = 0 To dr.FieldCount - 1

    lstitem =

    New ListViewItem(dr.Item(i).ToString)

    For ii = 1 To dr.FieldCount - 1

    lstitem.SubItems.Add(dr.Item(ii).ToString)

    Next

    lst.Items.Add(lstitem)

    Exit For

    Next

    End While

    dr.Close()

    End Sub

    Sub AddNewRecord(ByVal tbl As String, ByVal ParamArray Data() As String)

    Dim cm As New SqlClient.SqlCommand

    Dim da As New SqlClient.SqlDataAdapter

    Dim ds As New DataSet()

    Dim Temp As String

    Dim FTemp As String

    Try

    ds =

    New DataSet(tbl)

    da =

    New SqlClient.SqlDataAdapter("select * from " & tbl, cnn)

    da.Fill(ds, tbl)

    Dim i As Integer

    For i = 0 To UBound(Data)

    Dim fieldName = ds.Tables(tbl).Columns(i).ColumnName ' find caption of field name

    Temp = Temp & fieldName &

    ","

    FTemp = FTemp &

    "'" & Data(i) & "'" & ","

    Next

    Temp = Strings.Left(Temp, Len(Temp) - 1)

    FTemp = Strings.Left(FTemp, Len(FTemp) - 1)

    Dim sql As String

    sql =

    "Insert into " & tbl & "(" & Temp & ")" & " Values(" & FTemp & ")"

    cm.CommandText = sql

    cm.Connection = cnn

    cm.ExecuteNonQuery()

    Catch ex As Exception

    MsgBox(ex.Message)

    End Try

    End Sub

    Sub UpDateDataToTable(ByVal tbl As String, ByVal FieldCon As String, ByVal ValueCon As String, ByVal ParamArray Data() As String)

    Try

    Dim Temp As String

    Dim cm As New SqlClient.SqlCommand

    Dim da As New SqlClient.SqlDataAdapter

    Dim ds As New DataSet()

    ds =

    New DataSet(tbl)

    da =

    New SqlClient.SqlDataAdapter("select * from " & tbl, cnn)

    da.Fill(ds, tbl)

    Dim i As Integer

    For i = 0 To UBound(Data)

    Dim fieldName = ds.Tables(tbl).Columns(i).ColumnName ' find caption of field name

    Temp = Temp & fieldName &

    "='" & Data(i) & "',"

    Next

    Temp = Strings.Left(Temp, Len(Temp) - 1)

    cm.CommandText =

    "update " & tbl & " set " & Temp & " where " & FieldCon & "='" & ValueCon & "'"

    cm.Connection = cnn

    cm.ExecuteNonQuery()

    Catch ex As Exception

    MsgBox(ex.Message)

    End Try

    End Sub

    End

    Module

    --------------------------------------------------------------------------------------------------------------------------------------------------------

    • Form1 Code need 4 textbox,one Listview,2 Error provider,8 command Button, 1 Label name lblrecord
    • Captiontext :New , Update, delete, Save, |<, <<, >>, >|

    Public Class Form1

    Private WithEvents button1 As New Button

    Private mouseX, mouseY As Integer

    Private myMouseDown As Boolean

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

    Dim Path As String

    Path = System.IO.Directory.GetCurrentDirectory &

    "\TestDb.mdb"

    DBConnection(Path)

    TransferData2txt(

    Me, "ProductInfo", 0, "TextBox1", "TextBox2", "TextBox3", "TextBox4")

    showDataTolst(

    "ProductInfo", Me.Lst, Optionshow.SHowAllFields)

    'Lst.Bounds = New Rectangle(New Point(100, 10), New Size(300, 200))

    Me.FormBorderStyle = Windows.Forms.FormBorderStyle.None

    End Sub

    Private Sub CmdFirst_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CmdFirst.Click

    Lst.Items(LocPos).Selected =

    False

    LocPos = 0 :

    Me.lblrecord.Text = "1 / " & TotalPos + 1

    TransferData2txt(

    Me, "ProductInfo", LocPos, "TextBox1", "TextBox2", "TextBox3", "TextBox4")

    Lst.Items(LocPos).Selected =

    True

    End Sub

    Private Sub CmdLast_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles CmdLast.Click

    Lst.Items(LocPos).Selected =

    False

    LocPos = TotalPos :

    Me.lblrecord.Text = TotalPos + 1 & " / " & TotalPos + 1

    TransferData2txt(

    Me, "ProductInfo", LocPos, "TextBox1", "TextBox2", "TextBox3", "TextBox4")

    Lst.Items(LocPos).Selected =

    True

    End Sub

    Private Sub CmdNext_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles CmdNext.Click

    Lst.Items(LocPos).Selected =

    False

    If LocPos >= TotalPos Then

    lblrecord.Text = TotalPos + 1 &

    " OF " & TotalPos + 1

    Else

    LocPos = LocPos + 1

    lblrecord.Text = LocPos + 1 &

    " / " & TotalPos + 1

    TransferData2txt(

    Me, "ProductInfo", LocPos, "TextBox1", "TextBox2", "TextBox3", "TextBox4")

    Lst.Items(LocPos).Selected =

    True

    End If

    End Sub

    Private Sub CmdPre_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CmdPre.Click

    Lst.Items(LocPos).Selected =

    False

    If LocPos = 0 Then

    lblrecord.Text = 1 &

    " OF " & TotalPos + 1

    Else

    LocPos = LocPos - 1

    lblrecord.Text = LocPos + 1 &

    " / " & TotalPos + 1

    TransferData2txt(

    Me, "ProductInfo", LocPos, "TextBox1", "TextBox2", "TextBox3", "TextBox4")

    Lst.Items(LocPos).Selected =

    True

    End If

    End Sub

     

    Private Sub CmdNew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CmdNew.Click

    TextBox1.Text = IDcreator(

    "ProductInfo", "Pro", "-", "0000", "ProID")

    TextBox2.Clear() : TextBox3.Clear() : TextBox4.Clear()

    End Sub

    Private Sub CmdSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CmdSave.Click

    If TextBox3.Text = "" Or IsNumeric(TextBox3.Text) = False Then

    ErrorProvider1.SetError(TextBox3,

    "Invalid Data ! Please Check Your Data")

    ElseIf TextBox4.Text = "" Or IsNumeric(TextBox4.Text) = False Then

    ErrorProvider2.SetError(TextBox4,

    "Invalid Data ! Please Check Your Data")

    Else

    AddNewRecord(

    "Productinfo", TextBox1.Text, TextBox2.Text, TextBox3.Text, TextBox4.Text)

    showDataTolst(

    "ProductInfo", Me.Lst, Optionshow.SHowAllFields)

    End If

    End Sub

    Private Sub CmdDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CmdDelete.Click

    DeleteData(

    "ProductInfo", "Proid", TextBox1.Text, CustomDel.DelCustom)

    showDataTolst(

    "ProductInfo", Me.Lst, Optionshow.SHowAllFields)

    End Sub

    Private Sub CmdUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CmdUpdate.Click

    UpDateDataToTable(

    "ProductInfo", "Proid", TextBox1.Text, TextBox1.Text, TextBox2.Text, TextBox3.Text, TextBox4.Text)

    showDataTolst(

    "ProductInfo", Me.Lst, Optionshow.SHowAllFields)

    End Sub

     

    Private Sub Lst_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Lst.SelectedIndexChanged

    Dim i%

    i = Lst.FocusedItem.Index

    'MsgBox(Lst.Items(i).ToString)

    TransferData2txt(

    Me, "ProductInfo", i, "TextBox1", "TextBox2", "TextBox3", "TextBox4")

    End Sub

     

    Private Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click

    Me.Close()

    End Sub

    Private Sub Form1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles MyBase.MouseDown

    myMouseDown =

    True

    mouseX = Cursor.Position.X -

    Me.Location.X

    mouseY = Cursor.Position.Y -

    Me.Location.Y

    End Sub

    Private Sub Form1_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles MyBase.MouseMove

    Static LastCursor As Point

    Dim NowCursor As Point = New Point(Cursor.Position.X, Cursor.Position.Y)

    If Point.op_Inequality(NowCursor, LastCursor) Then

    If myMouseDown Then

    Me.Location = New System.Drawing.Point(Cursor.Position.X - mouseX, Cursor.Position.Y - mouseY)

    End If

    LastCursor = Cursor.Position

    End If

    End Sub

    Private Sub Form1_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles MyBase.MouseUp

    myMouseDown =

    False

    End Sub

    End Class

    i hope you cam customize this code with your own project  thanks

    if this is not enough pls give some idea ...na

    from Anatha1

  4. 08 Aug 2007 at 10:20

    Hi..

    I using ListView in C#.

    I tried to add text into certain colum in ListView.

    For example: I have 3 columns, Column1, Column2, Column3.

    I want to insert "TEST1"  and "TEST2" in Column2

    How can I going to do in C#?

    Thank you

    Halina

  5. 05 Jul 2007 at 19:14

    I found that the following code didn't work for me

    ListView1.ListItems.Remove(ListView1.SelectedItem) '// removes the selected item

    I had to use

    ListView1.ListItems.Remove(ListView1.SelectedItem.Index) 

    Also  - it wasn't obvious to me to start with  ( I'm a newbie to listviews )

    but to  'get at' the data in the views one had to use

    ListView1.ListItems.Item(x)    where  x is a valid number in the  range 1 to ListView1.ListItems.Count  (NOT   0 to .Count - 1 as in normal Visual Basic)

     Cheers

    Maxjonz

  6. 04 Jul 2007 at 07:34

    I would like to know whether there is any way to change change font/back ground color for individual subitems in a listview control.

    Regards
    Jyotiraditya

  7. 08 Nov 2006 at 06:14

    Okay, something I'm completely lost on and can't seem to find any info on.  If I assign a unique key to every item in the listview box with the add method, how do I later acess an item in the list by that key instead of by the index?  I see how to determine what the key is for an item (after I've referenced the item by index), but not how to directly reference an item by the key.

    My problem is that I have a sorted listview with multiple columns.  Because of having the list sorted, I can never be sure of the specific index that an item may get added at.  Specifically, when trying to add the subitems, after adding the main item, I can't just rely on the index of the main item.  Normally the sub items would be added using a line like this.

    lstview.listitems(i).subitems(1) = sSubItemText

    But when I added the main item, that index could be anywhere in the list since it's a sorted list.  So I figured I'd need to use the key, but I can't figure out how to reference a specific list item by the key.

    Thank you!

     

  8. 06 Oct 2006 at 03:12

    I also get error when i tried the code above
    if you're having problem with that code try this one

    ListView1.ListItems.Remove (ListView1.SelectedItem.Index)
    this is the code i use and it worked!

    this site is really cool, i learn a lot







  9. 12 Aug 2005 at 18:29

    Dear Sir:


    Your Tutorial on Listviews is very interesting, and I will learn something from it.  I am a VB6 Freshman, and have developed an Amortization program that is working well, but i decided to expand its features by incorporating the flexibility for the User to dictate when Extra Principal payment are to be made and in what amounts.


    I started using a Listview to draw the Payment numbers, and Dates (as started from a Monthview), and allow the User to then select in which  Payment numbers they will make an Extra Payment, and entered an amount which could vary from selection to selection of Payment numbers.


    The AMortziation program will be default schedule the amortization with ExtraPayments at zero, according to the number of Years (Term), and Periods of months in a year (Months).


    How do I draw these data from the FlexGrid to the Listview so that the User can checkmark his selections???


  10. 17 Jun 2005 at 04:58


    hi......
    i have some question and need to solve immediatley ....
    i want to double click on listview and after that will show new form and what i click in listview will displayed on that's new form.



    can someone help me? please... please ... please


    sorry for bad english, i hope someone will understand what i want, thanks so much.......

  11. 17 May 2005 at 21:39

    My version of MSVB6 does'nt allow me to use the code

    Code:
    ListView1.ListItems.Remove (ListView1.SelectedItem)

    (getting error).


    Looking at the syntax, the Remove-method requires an Index for the item to remove, but here an Item has been put as a param.
    So, I changed the code to:

    Code:
    ListView1.ListItems.Remove(ListView1.SelectedItem.Index)

    which worked!


    (sorry about the spelling etc. - I'm from Denmark!)


    Best regards, Jonas (aka. Juke)

  12. 22 Oct 2004 at 18:16

    I need to know how to allow the rows to be reordered (drag and drop) in either this or (preferrably) a Listbox. I can make the columns reorder-able but that's no help. (I'm only even using one column.)

  13. 18 Aug 2004 at 01:45

    Quote:
    I'm having the same problem. There's no .Columns property/method (using .ColumnHeaders does the same thing) and no Details option under View.


    i have never heard of this problem..
    you might want to check your virsion of VB or VS.
    i do believe i know that some commercial virsions (ones you get with books) don't let you make your own controls but I don't know about your situation buddy. I would try installing a different virsion unless you bought your virsion hehe. If you did purchase it, try contacting Microsoft.

  14. 02 Jun 2004 at 07:27

    I have a list viewcontrol in my application. Currently the user can the minimize the columnheader  width to zero. I want to restrict the user to minimize the column header to a particular point . How can this be achieved?


    Any replies would be appreciated. It is urgen
    -Thanks

  15. 08 May 2004 at 15:19

    I'm having the same problem. There's no .Columns property/method (using .ColumnHeaders does the same thing) and no Details option under View.

  16. 01 Feb 2004 at 17:22

    This one took me a while but it's as easy as one line of code.


    When setting the "selected" value to True:


    ListView1.SelectedItem.Selected = True


    add the following line of code right after:


    ListView1.SelectedItem.EnsureVisible


    remember to change "ListView1" to the name of your ListView control

  17. 29 Oct 2003 at 12:09

    set View property of ListView to 'Details'

  18. 29 Sep 2003 at 04:38
    HI,

         I want to print listview control content using printdocument , printpreviewdialog in vb.net.
    how can i see the prerview of listview using printpreviewdialog?
    Through printpreviewdialog i want to take printout.

    i did like this..........

       Private Sub ButtonPrint_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonPrint.Click
           PrintPreviewDialog1.Document = PrintDocument1
           PrintPreviewDialog1.FormBorderStyle = FormBorderStyle.Fixed3D
           PrintPreviewDialog1.SetBounds(ClientRectangle.X, ClientRectangle.Y,   ClientRectangle.Width + 50, ClientRectangle.Height + 50)
           PrintPreviewDialog1.PrintPreviewControl.Zoom = 1.0
           PrintPreviewDialog1.ShowDialog()
    End Sub

    Private Sub PrintDocument1_PrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
           Dim myPaintArgs As New PaintEventArgs(e.Graphics, New Rectangle(New Point(0, 0), Me.Size))
           Me.InvokePaint(ListView1, myPaintArgs)
       End Sub


    but it is not working. the balnk printpreviewdialog comming...
    please help me ...

    Thank you.
  19. 15 Sep 2003 at 12:37

    Help!
    I have a ListView control in my VB6 Form that is in report view and I am attempting to do a searh. I am able to find the ListItem I want, and even set the selected to true, but if the item is out of view on the listview, I cannot find a way to make the listview automatically scroll to that item.

  20. 15 Sep 2003 at 02:18

    Hi,


    I am trying make listview perform like the listbox.


    In list box i usually assign a value to the data field so that when i need to retrieve the data from the search field i could simply pull the data from the listbox. Its like a key which cannot be seen on the screen.


    e.g. lstSearchResults.ItemData(lstSearchResults.ListCount - 1) = rsUser("tableID")


    Now i trying to apply the similar concept to the listview but aint sure on how to go about doing so. Any one have any idea on how to go about doing so or any refreshing ideas


    Thank You in advance






  21. 26 Aug 2003 at 22:44

    ListView1.Columns.Add("Column Name",Width As Integer,Alignment)


    See Ya

  22. 21 Aug 2003 at 12:20

    I did the following
    ListView1.Add 1,,"my value"

  23. 21 Aug 2003 at 12:18

    Using VB.NET


    I have a ListView with several columns.


    Two columns contain integer values, while the remaining contain string values.


    I am confused as to how I would provide functionality to sort columns based on the column header the user has clicked in both Ascending and Descending formats.  


    If anyone could offer some useful code, or suggestions as how this can best be accomplished, it would be much appreciated.


    Regards,


    Owen

  24. 21 Aug 2003 at 12:13

    Could you post a link to the GREAT Article.


    THanks,


    Owen

  25. 10 Jul 2003 at 16:57

    I have been trying to add column headers at design time to a listView control. I'm able to set it using the Column Headers tab under the properties page, but no headers are visible either in design mode or at run time.  


    Any thoughts would be terribly appreciated.

  26. 15 Feb 2003 at 02:35

    im sorta new at Visual Basic, and i've been trying to get this to work for a long time, but its sorta confusing.


    Im trying to make my program open a csv file in the form_load procedure. If it doesn't find it, it'll make a new one (this itself doesn't even work). This csv file will hold a 2-dimensional array in it, which will then be displayed in a listview control.


    What im trying to get, more than anything else, is how to get the array to display in the listview control


    I GREATLY appreciate any and all help i can get with this.


    Thanx

  27. 23 Dec 2002 at 03:04

    I was struggling around the entire internet to find useful stuff on Listview. Finally I came to this web pages and it solved all my queries.
    Indeed, the most useful article compared to any on the entire Internet.

  28. 21 Nov 2002 at 13:38

    It does work if you use it right. It's actually a lot more complicated than it should be, in my opinion. Each listitem can have many subitems, and you can put text, icons or a combination. The only thing that I haven't been able to do is to change the order of the items in a column. Icons are first, followed by the text (if any). If you need an example, I can zip and email you a small project that will put several rows in. It even puts the icon into the heading. Let me know at: gmorris61@carolina.rr.com

  29. 21 Nov 2002 at 12:17

    I still dont get how are icons added to any column. I tried doing the second Add method suggested by GWMorris, but it doesnt work. Any ideas of how to go about it?
    Sam

  30. 06 Nov 2002 at 17:49

    By far the best explanation ive ever come accross, if only everything else was that simply explained!!

  31. 28 Oct 2002 at 03:11

    Hi


    I need a table (whether its using grid or listview controls) bound to a datasource (either at design-time or at run-time) in which at least 2 columns of data will display as checkboxes the values of boolean (Yes/No in Access) type fields.


    Please help.

  32. 10 Oct 2002 at 05:04
    I have a historic listview and I would like to add a listitem at the top of the listview - Is it possible? (Without resort / Moving all item one down)

    In hope of a quick response ;-)
    Carsten Stiller
    Denmark
  33. 18 Sep 2002 at 11:18
    First, set the FullRowSelect property of the ListView control to true. This lets the user select the item by clicking on any of the columns instead of having to click on the first column.

    Next place the code you will use to display the details in the DblClick event of the ListView control. To obtain the text of the first column of the item selected, use ListView1.SelectedItem.Text. Likewise you can obtain the key using ListView1.SelectedItem.key or the index using ListView1.SelectedItem.index.

    If the information you need is in one of the other columns, use ListView1.SelectedItem.SubItems(1) (1 being the second column, 2 the third, etc).
  34. 03 Jul 2002 at 13:57
    I would really like to know if this is possible as well.
  35. 12 Jun 2002 at 02:05

    [2]14[/2]
    Is it possible to double click an item on the ListView control ?
    I have 3 columns in the ListView Control. My idea is to display the seach results in the ListView.
    So as to let user be able to double click on any one of the rows to view its details.
    pls help!!

  36. 29 May 2002 at 09:07

    I can display Icon or checkBox in the ListView ,but how to loading lebel in ListView?
    When I chick Botton, It can be auto loading a lebel by I want, I need help!!


    Hope you can help me , Thank you!!

  37. 25 May 2002 at 09:52

    How do I display a combo box in one of the subitems of a listview.
    I know that I will have to subclass, but I dont know how to.


    Can you help?

  38. 11 Apr 2002 at 05:49

    Excellent, just what I needed, very complete

  39. 02 Apr 2002 at 02:34

    Thanks

  40. 01 Apr 2002 at 19:33

    It is easy once you realize that there are two ways to put in a subitem.
    Listview1.ListItems(2).SubItems(1) = "addsubitem" is the easiest, but no way to add an icon.
    Listview1.ListItems(1).ListSubItems.Add , , "addsubitem", 1 will do it. the Add method gives
    several options that the other syntax doesn't, but other than that, they both work equally well.

  41. 19 Mar 2002 at 15:46

    Hi I have a problem with ListView and Printer


    What i want to do is simple....I want that when i look at my listview in my program and there data in it i want to print it... I want to print all the form and i want to see the data in the listview when its printing....cause now when im printing the form....the listview is empty...What i want to do is like a printscrenn....i just want to see the data that we saw in the listview..Thanks for help

  42. 07 Mar 2002 at 23:09

    Try this:


    listview.SelectedItem.Index


    should return the row number

  43. 20 Feb 2002 at 03:14

    my question is....how can i view selected row...i want to view as a data report after double clicking the row that i've select....thanks...

  44. 14 Feb 2002 at 12:54

    Hi !
    I looking for a way to put icons in any column of a listview ... For now I can put one ine the first col
    but how to do for an another one ?
    thanks for any response.

  45. 13 Feb 2002 at 04:09

    i have a listview control
    i want to set a background image for that
    but it is not accepting the animated gif image
    i new my listview with a animated image
    if it is possible, give me how can i do it


    regards
    vasanth

  46. 13 Feb 2002 at 04:07

    i have a listview control
    i want to set a background image for that
    but it is not accepting the animated gif image
    i new my listview with a animated image
    if it is possible, give me how can i do it


    regards
    vasanth

  47. 04 Feb 2002 at 20:23

    I have a listview that updates when a node is clicked in a treeview control. The problem is that when in icon or small icon view, the icons line up down the middle of page of the control. The text that is associated with the icons are fairly long (+20) and wraps around the label. I just want the icons to snap to the left top side. Also the scrollbars won't be displayed unless I change the flatscroll bar property from false to to true and then in reverse, after I have resized the listview. Is there any way of making these icons line up other than the properties of the control in VB6? I have tried a few WinAPI's but they seem to only apply to list or report view.

  48. 14 Dec 2001 at 11:55

    Hello Samir...
       Yes it is quite possible to do exactly what you want.
       You just concentrate on LabelEdit property and events associated with (like BeforeLabelEdit  
       AfterLabelEdit ) and on StartLabelEdit method.
       I hope you can get it.


       All the best....
       cheers...


     

  49. 27 Nov 2001 at 08:07
    Is there anyway to modify (add,remove,edit) the ListView items during runtime , directly by clicking at the perticular item (someting similar to excel sheet) .
  50. 01 Jan 1999 at 00:00

    This thread is for discussions of ListView Control.

Leave a comment

Sign in or Join us (it's free).

James Crowley James first started this website when learning Visual Basic back in 1999 whilst studying his GCSEs. The site grew steadily over the years while being run as a hobby - to a regular monthly audience ...
AddThis

Related discussion

Related podcasts

  • Christian Beauclair

    14 mai 2008 (�mission #0074) ::.Christian Beauclair: Stratégies de migration VB6 vers .NET Nous discutons avec Christian Beauclair des stratégies de migration VB6 vers .NET. Entre autres, nous discutons comment utiliser le "VB 6 Code Advisor" et le "Interop Forms Toolkit" pour ajouter la puiss...

Want to stay in touch with what's going on? Follow us on twitter!