Solved

Vb.net Listview

Posted on 2016-07-19
9
78 Views
Last Modified: 2016-07-20
HI Experts

I have an SQL statement
SELECT Name, Address, Suburb, State FROM ADDRESSES 

Open in new window

Is there a way to add the SQL Select Field names to a Listview
e.g
me.listview.Columns.Add(SQL.Field(0), 100, HorozontalAlignment.left)
me.listview.Columns.Add(SQL.Field(1), 100, HorozontalAlignment.left)

Thanks
0
Comment
Question by:Kevinfeening
  • 3
  • 3
  • 2
  • +1
9 Comments
 
LVL 49

Expert Comment

by:Ryan Chong
ID: 41720206
what's the Object type for your object SQL ?

quick guess, you probably can try: SQL.Field(0).Name ?
0
 

Author Comment

by:Kevinfeening
ID: 41720287
In SQL server you run a script and it adds the Column headers in VB when the user can change the SQL from
 
SELECT Name, Address, Suburb, State FROM ADDRESSES 

Open in new window


To

 
SELECT Number, Name, Address, Suburb, State, Postcode FROM ADDRESSES 

Open in new window


How do you get the Column Header Number, Name etc and number of columns 6
0
 
LVL 49

Expert Comment

by:Ryan Chong
ID: 41720296
I think I'm not clear enough in my question above.

what I mean is:

>>SQL.Field(0)

what is this SQL object?

To answer your other questions we need to understand what is this object.
0
 
LVL 11

Expert Comment

by:ROMA CHAUHAN
ID: 41720298
Hi Kevinfeening,

To bind listview with sql result, you'll have to take the table returned from sql in a datatable and bind your listview with that datatable.

Try below code by passing your connection string, your sql query and your listview.
        Dim constr As String = "Put your connection string here"
        Dim ds As New DataSet
        Dim con As New SqlClient.SqlConnection(constr)
        con.Open()
        Dim sqladap As New SqlClient.SqlDataAdapter("SELECT Number, Name, Address, Suburb, State, Postcode FROM ADDRESSES ", con)
        sqladap.Fill(ds)
 
        For i As Integer = 0 To ds.Tables(0).Columns.Count – 1
            ListView1.Columns.Add(ds.Tables(0).Columns(i).ToString())
        Next
        For i As Integer = 0 To ds.Tables(0).Rows.Count – 1
            Dim listRow As New ListViewItem
            listRow.Text = ds.Tables(0).Rows(i)(0).ToString()
            For j As Integer = 1 To ds.Tables(0).Columns.Count – 1
                listRow.SubItems.Add(ds.Tables(0).Rows(i)(j).ToString())
            Next
            ListView1.Items.Add(listRow)
        Next

Open in new window

0
What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

 

Author Comment

by:Kevinfeening
ID: 41720299
No it was a example of what I thought could be done no such thing as SQL.Field(0)
its a plain SQL SELECT statement which runs in 2008 Server and I need to get the heading when running in VB.net
using Dim Reader as Data.IDaterReader = DataConnector.GetReader(SQL,Nothing)

Do While reader.read = true 
loop

Open in new window

0
 
LVL 11

Expert Comment

by:ROMA CHAUHAN
ID: 41720302
Here columns in datatable will be same as what you are getting from your sql query. You can use column name of datatable in your list view.
0
 
LVL 49

Accepted Solution

by:
Ryan Chong earned 350 total points
ID: 41720307
>>Dim Reader as Data.IDaterReader = DataConnector.GetReader(SQL,Nothing)

example;

use : Reader.FieldCount to get column count.

use: Reader.GetName(0) to get the column name
0
 
LVL 32

Assisted Solution

by:it_saige
it_saige earned 150 total points
ID: 41721394
In all honesty, the ListView is a terrible control for databinding items that have multiple displayable properties.  That being stated, we can accomodate the sql query results by using a datatable and filling the list view from it; e.g. -

Form1.vb -
Imports System.Data.SqlClient

Public Class Form1
	Dim table As New DataTable()

	Private Sub OnLoad(sender As Object, e As EventArgs) Handles MyBase.Load
		LoadDataTable()
		LoadListView1()
	End Sub

	Private Sub LoadDataTable()
		Using connection As New SqlConnection("Data Source=.;Initial Catalog=EE_Q28958447;Integrated Security=True;Pooling=False")
			connection.Open()
			Using da As New SqlDataAdapter("SELECT Name As Name, Address, Suburb, State FROM ADDRESS", connection)
				da.Fill(table)
			End Using
			connection.Close()
		End Using
	End Sub

	Private Sub LoadListView1()
		If table IsNot Nothing Then
			ListView1.View = View.Details
			ListView1.GridLines = True
			ListView1.FullRowSelect = True
			For Each column As DataColumn In table.Columns
				ListView1.Columns.Add(column.ColumnName, 100, HorizontalAlignment.Left)
			Next

			For Each row As DataRow In table.Rows
				Dim item As New ListViewItem(row("Name").ToString())
				item.SubItems.Add(row("Address").ToString())
				item.SubItems.Add(row("Suburb").ToString())
				item.SubItems.Add(row("State").ToString())
				ListView1.Items.Add(item)
			Next
		End If
	End Sub
End Class

Open in new window

Form1.Designer.vb -
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class Form1
    Inherits System.Windows.Forms.Form

    'Form overrides dispose to clean up the component list.
    <System.Diagnostics.DebuggerNonUserCode()> _
    Protected Overrides Sub Dispose(ByVal disposing As Boolean)
        Try
            If disposing AndAlso components IsNot Nothing Then
                components.Dispose()
            End If
        Finally
            MyBase.Dispose(disposing)
        End Try
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
    <System.Diagnostics.DebuggerStepThrough()> _
    Private Sub InitializeComponent()
		Me.ListView1 = New System.Windows.Forms.ListView()
		Me.SuspendLayout()
		'
		'ListView1
		'
		Me.ListView1.Location = New System.Drawing.Point(13, 13)
		Me.ListView1.Name = "ListView1"
		Me.ListView1.Size = New System.Drawing.Size(374, 273)
		Me.ListView1.TabIndex = 0
		Me.ListView1.UseCompatibleStateImageBehavior = False
		'
		'Form1
		'
		Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
		Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
		Me.ClientSize = New System.Drawing.Size(399, 298)
		Me.Controls.Add(Me.ListView1)
		Me.Name = "Form1"
		Me.Text = "Form1"
		Me.ResumeLayout(False)

	End Sub
	Friend WithEvents ListView1 As System.Windows.Forms.ListView
End Class

Open in new window

Produces the following output -Capture.JPGOfcourse, we could always add databinding capabilities to the ListView which would allow for us to just use the DataTable as a DataSource; e.g. -

Form1.vb -
Imports System.Data.SqlClient
Imports System.ComponentModel

Public Class Form1
	Dim table As New DataTable()

	Private Sub OnLoad(sender As Object, e As EventArgs) Handles MyBase.Load
		LoadDataTable()
		LoadListView1()
		LoadBindableListView1()
	End Sub

	Private Sub LoadDataTable()
		Using connection As New SqlConnection("Data Source=.;Initial Catalog=EE_Q28958447;Integrated Security=True;Pooling=False")
			connection.Open()
			Using da As New SqlDataAdapter("SELECT Name As Name, Address, Suburb, State FROM ADDRESS", connection)
				da.Fill(table)
			End Using
			connection.Close()
		End Using
	End Sub

	Private Sub LoadListView1()
		If table IsNot Nothing Then
			ListView1.View = View.Details
			ListView1.GridLines = True
			ListView1.FullRowSelect = True
			For Each column As DataColumn In table.Columns
				ListView1.Columns.Add(column.ColumnName, 100, HorizontalAlignment.Left)
			Next

			For Each row As DataRow In table.Rows
				Dim item As New ListViewItem(row("Name").ToString())
				item.SubItems.Add(row("Address").ToString())
				item.SubItems.Add(row("Suburb").ToString())
				item.SubItems.Add(row("State").ToString())
				ListView1.Items.Add(item)
			Next
		End If
	End Sub

	Private Sub LoadBindableListView1()
		If table IsNot Nothing Then
			BindableListView1.View = View.Details
			BindableListView1.GridLines = True
			BindableListView1.FullRowSelect = True
			BindableListView1.DataSource = table
		End If
	End Sub
End Class

'' Bindable list view.
'' 2003 - Ian Griffiths (ian@interact-sw.co.uk)
''
'' This code is in the public domain, and has no warranty.
''' <summary>
''' A ListView with complex data binding support.
''' </summary>
''' <remarks>
''' <p>Windows Forms provides a built-in <see cref="ListView"/> control,
''' which is essentially a wrapper of the standard Win32 list view. While
''' this is a very powerful control, it does not support complex data
''' binding. It supports simple binding, as all controls do, but simple
''' binding only binds a single row of data. The absence of complex
''' binding (i.e. the ability to bind to whole lists of data) is
''' disappointing in a class whose main purpose is to display lists of
''' things.</p>
'''
''' <p>This class derives from <see cref="ListView"/> and adds support
''' for complex binding, through its <see cref="DataSource"/> and
''' <see cref="DataMember"/> properties. These behave much like the
''' equivalent properties on the =<see cref="DataGrid"/> control.</p>
'''
''' <p>Note that the primary purpose of this control is to illustrate
''' data binding implementation techniques. It is NOT designed as an
''' industrial-strength control for use in production code. If you use
''' this in live systems, you do so at your own risk; it would almost
''' certainly be a better idea to look at the various professional
''' bindable grid controls on the market.</p>
''' </remarks>
Public Class BindableListView
	Inherits ListView

	Private _bindingList As IBindingList
	Private _changingIndex As Boolean
	Private _currencyManager As CurrencyManager
	Private _dataMember As String
	Private _dataSource As Object
	Private _properties As PropertyDescriptorCollection

	''' <summary>
	''' Raised when the DataSource property changes.
	''' </summary>
	Public Event DataSourceChanged As EventHandler

	''' <summary>
	''' Raised when the DataMember property changes.
	'''</summary>
	Public Event DataMemberChanged As EventHandler

	''' <summary>
	''' Identifies the item or relation within the data source whose
	''' contents should be shown.
	''' </summary>
	''' <remarks>
	''' <p>If the <see cref="DataSource"/> refers to a container of lists
	''' such as a <see cref="DataSet"/>, this property should be used to
	''' indicate which list should be shown.</p>
	''' 
	''' <p>Even when <see cref="DataSource"/> refers to a specific list,
	''' you can still set this property to indicate that a related table
	''' should be shown by specifying a relation name. This will cause
	''' this control to display only those rows in the child table related
	''' to the currently selected row in the parent table.</p>
	''' </remarks>
	<Category("Data")> _
	<Editor("System.Windows.Forms.Design.DataMemberListEditor, System.Design", GetType(System.Drawing.Design.UITypeEditor))> _
	Public Property DataMember() As String
		Get
			Return _dataMember
		End Get
		Set(value As String)
			If value IsNot Nothing AndAlso Not value.Equals(_dataMember) Then
				_dataMember = value
				SetDataBinding()
				OnDataMemberChanged(EventArgs.Empty)
			End If
		End Set
	End Property

	''' <summary>
	''' The data source to which this control is bound.
	''' </summary>
	''' <remarks>
	''' <p>To make this control display the contents of a data source, you
	''' should set this property to refer to that data source. The source
	''' should implement either <see cref="IList"/>,
	''' <see cref="IBindingList"/>, or <see cref="IListSource"/>.</p>
	'''
	''' <p>When binding to a list container (i.e. one that implements the
	''' <see cref="IListSource"/> interface, such as <see cref="DataSet"/>)
	''' you must also set the <see cref="DataMember"/> property in order
	''' to identify which particular list you would like to display. You
	''' may also set the <see cref="DataMember"/> property even when
	''' DataSource refers to a list, since <see cref="DataMember"/> can
	''' also be used to navigate relations between lists.</p>
	''' </remarks>
	<Category("Data")> _
	<TypeConverter("System.Windows.Forms.Design.DataSourceConverter, System.Design")> _
	Public Property DataSource() As Object
		Get
			Return _dataSource
		End Get
		Set(value As Object)
			If value IsNot Nothing AndAlso Not value.Equals(_dataSource) Then
				' Must be either a list or a list source
				If value IsNot Nothing AndAlso Not (TypeOf value Is IList) AndAlso Not (TypeOf value Is IListSource) Then
					Throw New ArgumentException("Data source must be IList or IListSource")
				End If
				_dataSource = value
				SetDataBinding()
				OnDataSourceChanged(EventArgs.Empty)
			End If
		End Set
	End Property

	''' <summary>
	''' Called when the DataSource property changes
	''' </summary>
	''' <param name="e">The EventArgs that will be passed to any handlers
	''' of the DataSourceChanged event.</param>
	Protected Overridable Sub OnDataSourceChanged(e As EventArgs)
		RaiseEvent DataSourceChanged(Me, e)
	End Sub

	''' <summary>
	''' Called when the DataMember property changes.
	''' </summary>
	''' <param name="e">The EventArgs that will be passed to any handlers
	''' of the DataMemberChanged event.</param>
	Protected Overridable Sub OnDataMemberChanged(e As EventArgs)
		RaiseEvent DataMemberChanged(Me, e)
	End Sub

	''' <summary>
	''' Handles binding context changes
	''' </summary>
	''' <param name="e">The EventArgs that will be passed to any handlers
	''' of the BindingContextChanged event.</param>
	Protected Overrides Sub OnBindingContextChanged(e As EventArgs)
		MyBase.OnBindingContextChanged(e)

		' If our binding context changes, we must rebind, since we will
		' have a new currency managers, even if we are still bound to the
		' same data source.
		SetDataBinding()
	End Sub

	''' <summary>
	''' Handles parent binding context changes
	''' </summary>
	''' <param name="e">Unused EventArgs.</param>
	Protected Overrides Sub OnParentBindingContextChanged(e As EventArgs)
		MyBase.OnParentBindingContextChanged(e)

		' BindingContext is an ambient property - by default it simply picks
		' up the parent control's context (unless something has explicitly
		' given us our own). So we must respond to changes in our parent's
		' binding context in the same way we would changes to our own
		' binding context.
		SetDataBinding()
	End Sub

	' Attaches the control to a data source.
	Private Sub SetDataBinding()
		' The BindingContext is initially null - in general we will not
		' obtain a BindingContext until we are attached to our parent
		' control. (OnParentBindingContextChanged will be called when
		' that happens, so this method will run again. This means it's
		' OK to ignore this call when we don't yet have a BindingContext.)
		If BindingContext IsNot Nothing Then

			' Obtain the CurrencyManager and (if available) IBindingList
			' for the current data source.
			Dim currencyManager As CurrencyManager = Nothing
			Dim bindingList As IBindingList = Nothing

			If DataSource IsNot Nothing Then
				If DataMember Is Nothing Then
					currencyManager = DirectCast(BindingContext(DataSource), CurrencyManager)
				Else
					currencyManager = DirectCast(BindingContext(DataSource, DataMember), CurrencyManager)
				End If
				If currencyManager IsNot Nothing Then
					bindingList = TryCast(currencyManager.List, IBindingList)
				End If
			End If

			' Now see if anything has changed since we last bound to a source.

			Dim reloadMetaData As Boolean = False
			Dim reloadItems As Boolean = False

			If Not Object.ReferenceEquals(currencyManager, _currencyManager) Then
				' We have a new CurrencyManager. If we were previously
				' using another CurrencyManager (i.e. if this is not the
				' first time we've seen one), we'll have some event
				' handlers attached to the old one, so first we must
				' detach those.
				If _currencyManager IsNot Nothing Then
					RemoveHandler currencyManager.MetaDataChanged, AddressOf OnMetaDataChanged
					RemoveHandler currencyManager.PositionChanged, AddressOf OnPositionChanged
					RemoveHandler currencyManager.ItemChanged, AddressOf OnItemChanged
				End If

				' Now hook up event handlers to the new CurrencyManager.
				' This enables us to detect when the currently selected
				' row changes. It also lets us find out more major changes
				' such as binding to a different list object (this happens
				' when binding to related views - each time the currently
				' selected row in a parent changes, the child list object
				' is replaced with a new object), or even changes in the
				' set of properties.
				_currencyManager = currencyManager
				If currencyManager IsNot Nothing Then
					reloadMetaData = True
					reloadItems = True
					AddHandler currencyManager.MetaDataChanged, AddressOf OnMetaDataChanged
					AddHandler currencyManager.PositionChanged, AddressOf OnPositionChanged
					AddHandler currencyManager.ItemChanged, AddressOf OnItemChanged
				End If
			End If

			If Not Object.ReferenceEquals(bindingList, _bindingList) Then
				' The IBindingList has changed. If we were previously
				' bound to an IBindingList, detach the event handler.
				If _bindingList IsNot Nothing Then
					RemoveHandler _bindingList.ListChanged, AddressOf OnListChanged
				End If

				' Now hook up a handler to the new IBindingList - this
				' will notify us of any changes in the list. (This is
				' more detailed than the CurrencyManager ItemChanged
				' event. However, we need both, because the only way we
				' know when the list is replaced completely is when the
				' CurrencyManager raises the ItemChanged event.)
				_bindingList = bindingList
				If bindingList IsNot Nothing Then
					reloadItems = True
					AddHandler bindingList.ListChanged, AddressOf OnListChanged
				End If
			End If

			' If a change occurred that means the set of properties may
			' have changed, reload these.
			If reloadMetaData Then
				LoadColumnsFromSource()
			End If

			' If a change occurred that means the set of items to be
			' shown in the list may have changed, reload those.
			If reloadItems Then
				LoadItemsFromSource()
			End If
			End If

	End Sub

	' Reload the properties, and build column headers for them.
	Private Sub LoadColumnsFromSource()
		' Retrieve and store the PropertyDescriptors. (We always go
		' via PropertyDescriptors when binding, and not the Reflection
		' API - this allows generic data sources to decide at runtime
		' what properties to present.) For data sources that don't opt
		' to have dynamic properties, the PropertyDescriptor mechanism
		' automatically falls back to Reflection under the covers.

		_properties = _currencyManager.GetItemProperties()


		' Build new column headers for the ListView.

		Dim headers As ColumnHeader() = New ColumnHeader(_properties.Count - 1) {}
		Columns.Clear()
		For column As Integer = 0 To _properties.Count - 1
			Dim columnName As String = _properties(column).Name

			' We set the width to be -2 in order to auto-size the column
			' to the header text. Bizarrely, this only works if we set
			' the width after adding the column. (That's we we're not
			' simply passing -2 to Add. The value passed - 0 in this case
			' - is irrelevant here.)
			Columns.Add(columnName, 0, HorizontalAlignment.Left)
			Columns(column).Width = -2
		Next
		' For some reason we seem to need to go back and set the
		' first column's Width to -2 (auto width) a second time.
		' It doesn't stick first time.
		Columns(0).Width = -2
	End Sub

	' Reload list items from the data source.
	Private Sub LoadItemsFromSource()
		' Tell the control not to bother redrawing until we're done
		' adding new items - avoids flicker and speeds things up.
		BeginUpdate()

		Try
			' We're about to rebuild the list, so get rid of the current
			' items.
			Items.Clear()

			' m_bindingList won't be set if the data source doesn't
			' implement IBindingList, so always ask the CurrencyManager
			' for the IList. (IList is all we need to retrieve the rows.)

			Dim items__1 As IList = _currencyManager.List

			' Add items to list.
			Dim nItems As Integer = items__1.Count
			For i As Integer = 0 To nItems - 1
				Items.Add(BuildItemForRow(items__1(i)))
			Next
			Dim index As Integer = _currencyManager.Position
			If index <> -1 Then
				SetSelectedIndex(index)
			End If
		Finally
			' In finally block just in case the data source does something
			' nasty to us - it feels like it might be bad to leave the
			' control in a state where we called BeginUpdate without a
			' corresponding EndUpdate.
			EndUpdate()
		End Try
	End Sub

	' Build a single ListViewItem for a single row from the source. (We
	' need to do this when constructing the original list, but this is
	' also called in the IBindingList.ListChanged event handler when
	' updating individual items.)
	Private Function BuildItemForRow(row As Object) As ListViewItem
		Dim itemText As String() = New String(_properties.Count - 1) {}
		For column As Integer = 0 To itemText.Length - 1
			' Use the PropertyDescriptors to extract the property value -
			' this might be a virtual property.

			itemText(column) = _properties(column).GetValue(row).ToString()
		Next
		Return New ListViewItem(itemText)
	End Function

	' IBindingList ListChanged event handler. Deals with fine-grained
	' changes to list items.
	Private Sub OnListChanged(sender As Object, e As ListChangedEventArgs)
		Select Case e.ListChangedType
			' Well, usually fine-grained... The whole list has changed
			' utterly, so reload it.
			Case ListChangedType.Reset
				LoadItemsFromSource()
				Exit Select
				' A single item has changed, so just rebuild that.
			Case ListChangedType.ItemChanged
				Dim changedRow As Object = _currencyManager.List(e.NewIndex)
				BeginUpdate()
				Items(e.NewIndex) = BuildItemForRow(changedRow)
				EndUpdate()
				Exit Select
				' A new item has appeared, so add that.
			Case ListChangedType.ItemAdded
				Dim newRow As Object = _currencyManager.List(e.NewIndex)
				' We get this event twice if certain grid controls
				' are used to add a new row to a datatable: once when
				' the editing of a new row begins, and once again when
				' that editing commits. (If the user cancels the creation
				' of the new row, we never see the second creation.)
				' We detect this by seeing if this is a view on a
				' row in a DataTable, and if it is, testing to see if
				' it's a new row under creation.
				Dim drv As DataRowView = TryCast(newRow, DataRowView)
				If drv Is Nothing OrElse Not drv.IsNew Then
					' Either we're not dealing with a view on a data
					' table, or this is the commit notification. Either
					' way, this is the final notification, so we want
					' to add the new row now!
					BeginUpdate()
					Items.Insert(e.NewIndex, BuildItemForRow(newRow))
					EndUpdate()
				End If
				Exit Select
				' An item has gone away.
			Case ListChangedType.ItemDeleted
				If e.NewIndex < Items.Count Then
					Items.RemoveAt(e.NewIndex)
				End If
				Exit Select
				' An item has changed its index.
			Case ListChangedType.ItemMoved
				BeginUpdate()
				Dim moving As ListViewItem = Items(e.OldIndex)
				Items.Insert(e.NewIndex, moving)
				EndUpdate()
				Exit Select
				' Something has changed in the metadata. (This control is
				' too lazy to deal with this in a fine-grained fashion,
				' mostly because the author has never seen this event
				' occur... So we deal with it the simple way: reload
				' everything.)
			Case ListChangedType.PropertyDescriptorAdded, ListChangedType.PropertyDescriptorChanged, ListChangedType.PropertyDescriptorDeleted
				LoadColumnsFromSource()
				LoadItemsFromSource()
				Exit Select
		End Select
	End Sub

	' The CurrencyManager calls this if the data source looks
	' different. We just reload everything.
	Private Sub OnMetaDataChanged(sender As Object, e As EventArgs)
		LoadColumnsFromSource()
		LoadItemsFromSource()
	End Sub

	' Called by the CurrencyManager when the currently selected item
	' changes. We update the ListView selection so that we stay in sync
	' with any other controls bound to the same source.
	Private Sub OnPositionChanged(sender As Object, e As EventArgs)
		SetSelectedIndex(_currencyManager.Position)
	End Sub

	' Change the currently-selected item. (I'm sure I'm missing a simpler
	' way of doing this... If anyone knows what it is, please let me
	' know!)
	Private Sub SetSelectedIndex(index As Integer)
		' Avoid recursion - we keep track of when we're already in the
		' middle of changing the index, in case the CurrencyManager
		' decides to call us back as a result of a change already in
		' progress. (Not sure if this will ever actually happen - the
		' OnSelectedIndexChanged method uses the m_changingIndex flag to
		' avoid modifying the CurrencyManager's Position when the change
		' in selection was caused by the CurrencyManager in the first
		' place. But it doesn't hurt to be defensive...)
		If Not _changingIndex Then
			_changingIndex = True
			SelectedItems.Clear()
			If Items.Count > index Then
				Dim item As ListViewItem = Items(index)
				item.Selected = True
				item.EnsureVisible()
			End If
			_changingIndex = False
		End If
	End Sub

	' Called by Windows Forms when the currently selected index of the
	' control changes. This usually happens because the user clicked on
	' the control. In this case we want to notify the CurrencyManager so
	' that any other bound controls will remain in sync. This method will
	' also be called when we changed our index as a result of a
	' notification that originated from the CurrencyManager, and in that
	' case we avoid notifying the CurrencyManager back!
	Protected Overrides Sub OnSelectedIndexChanged(e As EventArgs)
		MyBase.OnSelectedIndexChanged(e)

		' Did this originate from us, or was this caused by the
		' CurrencyManager in the first place. If we're sure it was us,
		' and there is actually a selected item (this event is also raised
		' when transitioning to the 'no items selected' state), and we
		' definitely do have a CurrencyManager (i.e. we are actually bound
		' to a data source), then we notify the CurrencyManager.

		If Not _changingIndex AndAlso SelectedIndices.Count > 0 AndAlso _currencyManager IsNot Nothing Then
			_currencyManager.Position = SelectedIndices(0)
		End If
	End Sub

	' Called by the CurrencyManager when stuff changes. (Yes I know
	' that's vague, but then so is the official documentation.)
	' At time of writing, the official docs imply that you don't need
	' to handle this event if your source implements IBindingList, since
	' IBindingList.ListChanged provides more details information about the
	' change. However, it's not quite as simple as that: when bound to a
	' related view, the list to which we are bound changes every time the
	' selected index of the parent changes, and to see that happen we
	' either have handle this event, or the CurrentChanged (also from the
	' CurrencyManager). So in practice you need to handle both.
	' It doesn't appear to matter whether you handle CurrentChanged or
	' ItemChanged in order to detect such changes - both are raised when
	' the underlying list changes. However, Mark Boulter sent me some
	' example code (thanks Mark!) that used this one, and he probably
	' knows something I don't about which is likely to work better...
	' So I'm doing what his code does and using this event.
	Private Sub OnItemChanged(sender As Object, e As ItemChangedEventArgs)
		' An index of -1 seems to be the indication that lots has
		' changed. (I've not found where it says this in the
		' documentation - I got this information from a comment in Mark
		' Boulter's code.) So we always reload all items from the
		' source when this happens.
		If e.Index = -1 Then
			' ...but before we reload all items from source, we also look
			' to see if the list we're supposed to bind to has changed
			' since last time, and if it has, reattach our event handlers.
			If Not Object.ReferenceEquals(_bindingList, _currencyManager.List) Then
				RemoveHandler _bindingList.ListChanged, AddressOf OnListChanged
				_bindingList = TryCast(_currencyManager.List, IBindingList)
				If _bindingList IsNot Nothing Then
					AddHandler _bindingList.ListChanged, AddressOf OnListChanged
				End If
			End If
			LoadItemsFromSource()
		End If
	End Sub
End Class

Open in new window

Form1.Designer.vb -
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class Form1
    Inherits System.Windows.Forms.Form

    'Form overrides dispose to clean up the component list.
    <System.Diagnostics.DebuggerNonUserCode()> _
    Protected Overrides Sub Dispose(ByVal disposing As Boolean)
        Try
            If disposing AndAlso components IsNot Nothing Then
                components.Dispose()
            End If
        Finally
            MyBase.Dispose(disposing)
        End Try
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
    <System.Diagnostics.DebuggerStepThrough()> _
    Private Sub InitializeComponent()
		Me.ListView1 = New System.Windows.Forms.ListView()
		Me.BindableListView1 = New EE_Q28958447.BindableListView()
		Me.SuspendLayout()
		'
		'ListView1
		'
		Me.ListView1.Location = New System.Drawing.Point(13, 13)
		Me.ListView1.Name = "ListView1"
		Me.ListView1.Size = New System.Drawing.Size(374, 124)
		Me.ListView1.TabIndex = 0
		Me.ListView1.UseCompatibleStateImageBehavior = False
		'
		'BindableListView1
		'
		Me.BindableListView1.DataMember = Nothing
		Me.BindableListView1.DataSource = Nothing
		Me.BindableListView1.Location = New System.Drawing.Point(13, 144)
		Me.BindableListView1.Name = "BindableListView1"
		Me.BindableListView1.Size = New System.Drawing.Size(374, 142)
		Me.BindableListView1.TabIndex = 1
		Me.BindableListView1.UseCompatibleStateImageBehavior = False
		'
		'Form1
		'
		Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
		Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
		Me.ClientSize = New System.Drawing.Size(399, 298)
		Me.Controls.Add(Me.BindableListView1)
		Me.Controls.Add(Me.ListView1)
		Me.Name = "Form1"
		Me.Text = "Form1"
		Me.ResumeLayout(False)

	End Sub
	Friend WithEvents ListView1 As System.Windows.Forms.ListView
	Friend WithEvents BindableListView1 As EE_Q28958447.BindableListView
End Class

Open in new window

Now produces the following output -Capture.JPGPersonally, I would just use a DataGridView which already has multi-property databinding built-in.

-saige-
0
 

Author Closing Comment

by:Kevinfeening
ID: 41721853
Simple and worked
Others more complicated but worked

Thanks All
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

When designing a form there are several BorderStyles to choose from, all of which can be classified as either 'Fixed' or 'Sizable' and I'd guess that 'Fixed Single' or one of the other fixed types is the most popular choice. I assume it's the most p…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Get people started with the process of using Access VBA to control Outlook using automation, Microsoft Access can control other applications. An example is the ability to programmatically talk to Microsoft Outlook. Using automation, an Access applic…
This lesson covers basic error handling code in Microsoft Excel using VBA. This is the first lesson in a 3-part series that uses code to loop through an Excel spreadsheet in VBA and then fix errors, taking advantage of error handling code. This l…

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now