Library tutorials & articles
ListView Control
By James Crowley, published on 14 Jul 2001
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!
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
[quote user="Maxjonz"]
I found that the following code didn't work for me
ListView1.ListItems.Remove(ListView1.SelectedItem) '// removes the selected itemI 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
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.
Imports
System.Data.OleDbImports
System.IOModule
Module1 Dim cnn As New OleDb.OleDbConnection Public LocPos As Integer Public TotalPos As Integer Sub DBConnection(ByVal PTH As String) Trycnn =
New OleDbConnection("Provider=microsoft.jet.oledb.4.0; data source='" & PTH & "'")cnn.Open()
Catch ex As ExceptionMsgBox(ex.Message, MsgBoxStyle.Information,
"") End End Try End Sub Public Enum CustomDelDellAll = 1
DelCustom = 2
End Enum Public Enum CtrlDorECtrlDiabled = 1
CtrlEnabled = 2
End Enum Public Enum OptionshowSHowAllFields = 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 StringSQLa =
"delete * from " & tblSQLc =
"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 Selectcm.Connection = cnn
cm.ExecuteNonQuery()
Catch ex As ExceptionMsgBox(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 errcm.CommandText =
"select * from " & tblcm.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) Thenct.Text = .Item(i).ToString
i = i + 1 :
Exit For End If Next End If Next End Withdr.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 Tryds =
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 tableTem = IDStyle & Connector & Format(RecordCount + 1, FormatNumber)
Dim i = 1 Doi = i + 1
cm.CommandText =
"select * from " & tbl & " where " & Field & " = '" & Tem & "'"cm.Connection = cnn
Dim rst As OleDb.OleDbDataReader = cm.ExecuteReader If rst.HasRows ThenTem = IDStyle & Connector & Format(RecordCount + i, FormatNumber)
rst.Close()
Else : IDcreator = Tem : Exit Function End If Loop Catch ex As ExceptionMsgBox(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 ColumnHeaderlst.View = View.Details
lst.Clear()
Select Case showOption Case 1 : Opt = Optionshow.SHowAllFieldsSql =
"select * from " & tbl Case 2 : Opt = Optionshow.SHowSomeField For a = 0 To UBound(SelectField)TemField = TemField & SelectField(a) &
"," NextTemField = Strings.Left(TemField, Len(TemField) - 1)
Sql =
"select " & TemField & " from " & tbl End Selectcm.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 nameColH =
New ColumnHeader()ColH.Text = fieldName
lst.Columns.Add(ColH)
Next For Each ColH In lst.ColumnsColH.Width = 90
Next Dim dr As OleDbDataReader = cm.ExecuteReader While dr.Read Dim lstitem As ListViewItem For i = 0 To dr.FieldCount - 1lstitem =
New ListViewItem(dr.Item(i).ToString) For ii = 1 To dr.FieldCount - 1lstitem.SubItems.Add(dr.Item(ii).ToString)
Nextlst.Items.Add(lstitem)
Exit For Next End Whiledr.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 Tryds =
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 nameTemp = Temp & fieldName &
","FTemp = FTemp &
"'" & Data(i) & "'" & "," NextTemp = Strings.Left(Temp, Len(Temp) - 1)
FTemp = Strings.Left(FTemp, Len(FTemp) - 1)
Dim sql As Stringsql =
"Insert into " & tbl & "(" & Temp & ")" & " Values(" & FTemp & ")"cm.CommandText = sql
cm.Connection = cnn
cm.ExecuteNonQuery()
Catch ex As ExceptionMsgBox(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 nameTemp = Temp & fieldName &
"='" & Data(i) & "'," NextTemp = Strings.Left(Temp, Len(Temp) - 1)
cm.CommandText =
"update " & tbl & " set " & Temp & " where " & FieldCon & "='" & ValueCon & "'"cm.Connection = cnn
cm.ExecuteNonQuery()
Catch ex As ExceptionMsgBox(ex.Message)
End Try End SubEnd
Moduleconnect 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()
Imports
System.Data.SqlClientModule
Module2 Dim cnn As New SqlClient.SqlConnection Public LocPos As Integer Public TotalPos As Integer Public Enum CustomDelDellAll = 1
DelCustom = 2
End Enum Public Enum OptionshowSHowAllFields = 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 StringSQLa =
"delete * from " & tblSQLc =
"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 Selectcm.Connection = cnn
cm.ExecuteNonQuery()
Catch ex As ExceptionMsgBox(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 errcm.CommandText =
"select * from " & tblcm.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) Thenct.Text = .Item(i).ToString
i = i + 1 :
Exit For End If Next End If Next End Withdr.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 Tryds =
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 tableTem = IDStyle & Connector & Format(RecordCount + 1, FormatNumber)
Dim i = 1 Doi = i + 1
cm.CommandText =
"select * from " & tbl & " where " & Field & " = '" & Tem & "'"cm.Connection = cnn
Dim rst As SqlClient.SqlDataReader = cm.ExecuteReader If rst.HasRows ThenTem = IDStyle & Connector & Format(RecordCount + i, FormatNumber)
rst.Close()
Else : IDcreator = Tem : Exit Function End If Loop Catch ex As ExceptionMsgBox(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 ColumnHeaderlst.View = View.Details
lst.Clear()
Select Case showOption Case 1 : Opt = Optionshow.SHowAllFieldsSql =
"select * from " & tbl Case 2 : Opt = Optionshow.SHowSomeField For a = 0 To UBound(SelectField)TemField = TemField & SelectField(a) &
"," NextTemField = Strings.Left(TemField, Len(TemField) - 1)
Sql =
"select " & TemField & " from " & tbl End Selectcm.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 nameColH =
New ColumnHeader()ColH.Text = fieldName
lst.Columns.Add(ColH)
Next For Each ColH In lst.ColumnsColH.Width = 90
Next Dim dr As SqlClient.SqlDataReader = cm.ExecuteReader While dr.Read Dim lstitem As ListViewItem For i = 0 To dr.FieldCount - 1lstitem =
New ListViewItem(dr.Item(i).ToString) For ii = 1 To dr.FieldCount - 1lstitem.SubItems.Add(dr.Item(ii).ToString)
Nextlst.Items.Add(lstitem)
Exit For Next End Whiledr.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 Tryds =
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 nameTemp = Temp & fieldName &
","FTemp = FTemp &
"'" & Data(i) & "'" & "," NextTemp = Strings.Left(Temp, Len(Temp) - 1)
FTemp = Strings.Left(FTemp, Len(FTemp) - 1)
Dim sql As Stringsql =
"Insert into " & tbl & "(" & Temp & ")" & " Values(" & FTemp & ")"cm.CommandText = sql
cm.Connection = cnn
cm.ExecuteNonQuery()
Catch ex As ExceptionMsgBox(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 nameTemp = Temp & fieldName &
"='" & Data(i) & "'," NextTemp = Strings.Left(Temp, Len(Temp) - 1)
cm.CommandText =
"update " & tbl & " set " & Temp & " where " & FieldCon & "='" & ValueCon & "'"cm.Connection = cnn
cm.ExecuteNonQuery()
Catch ex As ExceptionMsgBox(ex.Message)
End Try End SubEnd
Module--------------------------------------------------------------------------------------------------------------------------------------------------------
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 StringPath = 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.ClickLst.Items(LocPos).Selected =
FalseLocPos = 0 :
Me.lblrecord.Text = "1 / " & TotalPos + 1TransferData2txt(
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.ClickLst.Items(LocPos).Selected =
FalseLocPos = TotalPos :
Me.lblrecord.Text = TotalPos + 1 & " / " & TotalPos + 1TransferData2txt(
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.ClickLst.Items(LocPos).Selected =
False If LocPos >= TotalPos Thenlblrecord.Text = TotalPos + 1 &
" OF " & TotalPos + 1 ElseLocPos = LocPos + 1
lblrecord.Text = LocPos + 1 &
" / " & TotalPos + 1TransferData2txt(
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.ClickLst.Items(LocPos).Selected =
False If LocPos = 0 Thenlblrecord.Text = 1 &
" OF " & TotalPos + 1 ElseLocPos = LocPos - 1
lblrecord.Text = LocPos + 1 &
" / " & TotalPos + 1TransferData2txt(
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.ClickTextBox1.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 ThenErrorProvider1.SetError(TextBox3,
"Invalid Data ! Please Check Your Data") ElseIf TextBox4.Text = "" Or IsNumeric(TextBox4.Text) = False ThenErrorProvider2.SetError(TextBox4,
"Invalid Data ! Please Check Your Data") ElseAddNewRecord(
"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.ClickDeleteData(
"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.ClickUpDateDataToTable(
"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.MouseDownmyMouseDown =
TruemouseX = Cursor.Position.X -
Me.Location.XmouseY = 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 IfLastCursor = Cursor.Position
End IfEnd Sub
Private Sub Form1_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles MyBase.MouseUpmyMouseDown =
FalseEnd 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
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
I found that the following code didn't work for me
ListView1.ListItems.Remove(ListView1.SelectedItem) '// removes the selected itemI 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
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
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!
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
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???
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.......