Library tutorials & articles
ListView Control
Using Columns
The ListView control allows you to add columns of data to the list view. Normally, you know the columns you want, and can add them at design time. To do this, right click on the ListView control and click properties. This displays the property sheet. Now click on the Column Headers tab. Click on the Insert Column button, and fill out the data. The minimum data you need to add is the text to be displayed. It is also helpful if you add a value into the Key field, as you can then easily identify the column using that key. If you want, you can also add a Image index so an image will be displayed next to the column text (see using icons, below for more info)
If you want to add the columns at run time, you can use the ColumnHeaders collection and add them like adding list items (see above)
In order for the columns to be displayed, you need to set the View mode to Report. To do this at design time, view the properties and change View to Report. Note that the columns you have added will not be displayed at design time. Alternatively you can set the view at runtime:
ListView1.View = lvwReport
Add a few columns at design time, and add the code above, and the code you wrote in the Adding Items section to the form_load event. Run the project. You will notice that the items you have added, only has the text in the first column. To add values to other columns, you need to use the ListSubItems collection, which is a sub property of the ListItems collection (see Adding Items). For example:
ListView1.ListItems(1).ListSubItems.Add , "key1", "text1"
adds a sub item to the first item on the list with the key, Key1, and the text, Text1. You can also use the SubItems property as an easier method, if you only want to set the text:
ListView1.ListItems(1).SubItems(1) = "Text1"
This adds Text1 to the second column of the first item.
The following code adds the items shown in Adding Items, but also adds some extra data in the other columns:
' Set the View
ListView1.View = lvwReport
' Add the columns
With ListView1.ColumnHeaders
.Add , , "Name"
.Add , , "Surname"
.Add , , "Address"
End With
With ListView1.ListItems
' Add the normal text
.Add , , "Fred"
.Add , , "Sarah"
.Add , , "Paul"
End With
With ListView1
' Add a value to the second column to the first item on the
list ("Fred")
' (1) = First item on list
.ListItems(1).SubItems(1) = "Crowley"
.ListItems(2).SubItems(1) = "Ives"
.ListItems(3).SubItems(1) = "Smith"
' Add a value to the third column to the first item on the
list ("Fred")
' (1) = First item on list
.ListItems(1).SubItems(2) = "16 Liverpool Lane"
.ListItems(2).SubItems(2) = "102 England Street"
.ListItems(3).SubItems(2) = "1 Baker Street"
End With
Form1 should then look like this:
Of course, this is when you know what items you want to add. When you don't, you can loop through an array that has all the items in:
With ListView1
' Loop through name array
For i = 0 To UBound(NameArray)
.ListItems.Add i, ,NameArray(i)
Next
' Loop through surname array
For i = 0 To UBound(SurnameArray)
.ListItems(i).ListSubItems.Add i, , SurnameArray(i)
Next
' Loop through address array
For i = 0 To UBound(AddressArray)
.ListItems(i).ListSubItems.Add i, ,AddressArray(i)
Next
End With
Related articles
Related discussion
-
VB6 Runtime error 381 subsript out of range Error
by Uncle (2 replies)
-
passing and reading parameters from using Shell
by jigartoliya (0 replies)
-
Convert C++ code to VB6
by mawcot (4 replies)
-
listbox scrollbar
by Dennijr (10 replies)
-
Can you describe Above simple VB6 code?
by pramodmca09 (0 replies)
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...
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.......
My version of MSVB6 does'nt allow me to use the code
(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:
which worked!
(sorry about the spelling etc. - I'm from Denmark!)
Best regards, Jonas (aka. Juke)
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.)
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.
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
I'm having the same problem. There's no .Columns property/method (using .ColumnHeaders does the same thing) and no Details option under View.
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
set View property of ListView to 'Details'
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.
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.
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
ListView1.Columns.Add("Column Name",Width As Integer,Alignment)
See Ya
I did the following
ListView1.Add 1,,"my value"
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
Could you post a link to the GREAT Article.
THanks,
Owen
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.
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
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.
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
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
By far the best explanation ive ever come accross, if only everything else was that simply explained!!
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.
In hope of a quick response ;-)
Carsten Stiller
Denmark
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).
[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!!
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!!
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?
Excellent, just what I needed, very complete
Thanks
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.
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
Try this:
listview.SelectedItem.Index
should return the row number
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...
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.
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
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
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.
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...
This thread is for discussions of ListView Control.