Click here to Skip to main content
15,892,161 members
Articles / Desktop Programming / Win32

Save and Load the whole content of a ListView Control

Rate me:
Please Sign up or sign in to vote.
4.22/5 (8 votes)
23 Feb 2012CPOL8 min read 33K   1.4K   15  
Sometimes you have to save the content of a ListView to the user's filesystem. That's very easy to manage with the XmlText-Writer and Reader from the .Net Framework 2.0.
Option Strict On

Public Class frmMain
	Dim _invisibleColumnExists As Boolean = False
	ReadOnly _formSize As Size = New Size(380, 353)
	
	''' <summary>
	''' Adjusts all Headers in the given ListView
	''' </summary>
	''' <param name="lsv_">The ListView the Headers will be adjusted</param>
	''' <param name="alignment">The alignment to adjust</param>
	Private Sub AdjustHeaderAlignments(ByVal lsv_ As ListView, ByVal alignment As HorizontalAlignment)
		For i As Integer = 0 To lsv.Columns.Count - 1
			lsv.Columns(i).TextAlign = alignment
		Next
	End Sub

#Region "Save and load the content"

	Private Sub cmdSave_Click(sender As Object, e As EventArgs) Handles cmdSave.Click
		Dim dlg As New SaveFileDialog
		Dim errMsg As String = ""

		With dlg
			.DefaultExt = ".xml"
			.Filter = "All files|*.*"
			.RestoreDirectory = True
			.Title = "Save..."
		End With
	
		If dlg.ShowDialog = DialogResult.OK Then
			errMsg = ListViewContent.Save(lsv, dlg.FileName)

			If errMsg <> String.Empty Then MessageBox.Show("An error occured during operation")

		End If

	End Sub

	Private Sub cmdLoad_Click(sender As Object, e As EventArgs) Handles cmdLoad.Click
		Dim dlg As New OpenFileDialog
		Dim index As Integer = If(lsv.Groups.Count > 0, 1, 0)
		Dim errMsg As String = ""

		With dlg
			.DefaultExt = ".xml"
			.Filter = "All files|*.*"
			.RestoreDirectory = True
			.Title = "Save..."
		End With

		If dlg.ShowDialog = DialogResult.OK Then
			errMsg = ListViewContent.Load(lsv, dlg.FileName, False, True, True)

			If errMsg <> String.Empty Then
				MessageBox.Show(errMsg, "Error during operation")

				Exit Sub
			End If

			For i As Integer = 0 To lsv.Groups.Count - 1
				If lsv.Groups(i).Items.Count > 0 Then cmbGroups.Items.Insert(index, lsv.Groups(i).Header)
			Next

			If chkCenterColumnHeaderText.Checked Then
				AdjustHeaderAlignments(lsv, HorizontalAlignment.Center)

			Else
				AdjustHeaderAlignments(lsv, HorizontalAlignment.Left)

			End If

			If lsv.Columns(0).Width = 0 Then _invisibleColumnExists = True
		End If
	End Sub

#End Region

#Region "Manage the ListView control"

	Private Sub cmdAddToGroups_Click(sender As Object, e As EventArgs) Handles cmdAddToGroups.Click
		' If the trimmed text isn't an empty String, the new group is added to the ListView's Group-Collection
		If txtNewGroupName.Text.Replace("  ", "").Trim <> "" Then
			Dim index As Integer = If(lsv.Groups.Count > 0, 1, 0)

			lsv.Groups.Insert(index, New ListViewGroup(txtNewGroupName.Text, txtNewGroupName.Text))
			cmbGroups.Items.Insert(index, txtNewGroupName.Text)
			cmbGroups.SelectedIndex = index
		End If
	End Sub

	Private Sub cmdAddToLsv_Click(sender As Object, e As EventArgs) Handles cmdAddToLsv.Click
		' If the trimmed text isn't an empty String then the new item is added to the ListView
		If txtColumn1.Text.Replace("  ", "").Trim <> "" AndAlso txtColumn2.Text.Replace("  ", "").Trim <> "" Then

			' If the user doesn't want to show groups, they are disabled 
			If cmbGroups.SelectedItem Is "-None-" Or cmbGroups.SelectedIndex = -1 Then
				lsv.Items.Add(txtColumn1.Text).SubItems.Add(txtColumn2.Text)
				lsv.ShowGroups = False

			Else

				' If there is an "invisible" column, the new item has an empty column
				If _invisibleColumnExists Then
					Dim listItem As New ListViewItem("", 0, lsv.Groups(cmbGroups.SelectedItem.ToString))
					listItem.SubItems.Add(txtColumn1.Text)
					listItem.SubItems.Add(txtColumn2.Text)

					lsv.Items.Add(listItem)
					lsv.ShowGroups = True

				Else ' Otherwise there's now empty column for the new item
					Dim listItem As New ListViewItem(txtColumn1.Text, 0, lsv.Groups(cmbGroups.SelectedItem.ToString))
					listItem.SubItems.Add(txtColumn2.Text)

					lsv.Items.Add(listItem)
					lsv.ShowGroups = True
				End If

			End If
		End If
	End Sub

#End Region

#Region "Other"

	Private Sub frmMain_DoubleClick(sender As Object, e As EventArgs) Handles MyBase.DoubleClick
		Me.Size = _formSize	' Reset the size of the form to default Values
	End Sub

	Private Sub lsv_ColumnWidthChanging(sender As Object, e As ColumnWidthChangingEventArgs) Handles lsv.ColumnWidthChanging
		' If an "Invisible" Column exists, its size is set to 0 px, so that the user doesn't see it
		If e.ColumnIndex = 0 AndAlso _invisibleColumnExists Then
			e.Cancel = True
			e.NewWidth = 0
		End If
	End Sub

	Private Sub chkCenterColumnHeaderText_CheckedChanged(sender As Object, e As EventArgs) Handles chkCenterColumnHeaderText.CheckedChanged
		' If the user checks the CheckBox for centering the HeaderAlignments, they will be centered. Else it is left-aligned
		If chkCenterColumnHeaderText.Checked Then
			AdjustHeaderAlignments(lsv, HorizontalAlignment.Center)

		Else
			AdjustHeaderAlignments(lsv, HorizontalAlignment.Left)

		End If
	End Sub
	
#End Region

End Class

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions