Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Blogs | Beginners | Advertise with Us
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Team Foundation Server Hosting
Search :       Advanced Search »
Home » VB.NET » An editable GridView Control in VB.NET

An editable GridView Control in VB.NET

In this article we will take advantage of the XML classes available to us to persist the GridView control that we talked about in our first article in this series. The two classes we utilize in our code are XmlTextWriter and XmlTextReader. These classes enable us to save the information in a grid into an XML file and read an XML file into the grid.

Author Rank :
Page Views : 75504
Downloads : 1335
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
GridViewIICode.zip
 
 
Team Foundation Server Hosting
Become a Sponsor
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

If you've played with .NET a bit, you may have noticed Microsoft's hard push to utilize XML throughout the architecture.  In this article we will take advantage of the XML classes available to us to persist the GridView control. The two classes we utilize in our code are XmlTextWriter and XmlTextReader. These classes enable us to save the information in a grid into an XML file and read an XML file into the grid.



Figure 1 - The Editable GridView with Persistence.

The XmlTextWriter class has several useful functions that make creating an XML file less tedious.  Below is a table of the methods we take advantage of for writing out the GridView.

XmlTextWriter methods                             Description
WriteStartDocument(bool)

Writes the XML starting declaration. The bool tells whether the document includes the standalone property.
<?
xml version="1.0" standalone="no" ?>

WriteStartElement(string) Creates a node in the XML document with the starting element equal to the string passed
WriteAttributeString(string,string) Writes an attribute in the node with a name and a value
WriteEndElement() Matches the last node started with an ending element.

Table 1 - XmlTextWriter Methods used in the GridView

The XmlReader class enables us to read the XML files into our code.  It also has many convenient methods and properties  for walking through the XML nodes and extracting data from the XML document.  Below are the properties and methods we utilize for reading our GridView:

XmlTextReader methods and properties  

Description

bool Read() Reads the next XML node from the file  into an instance of the class for processing.  Returns false when it has read all the nodes
Name Name of the current node or attribute
Value current  node or attribute value
AttributeCount Number of attributes in the current node
MoveToAttribute(int index) Moves to the attribute in the current node indicated by the index.  The index is 0 based

Table 2 - XmlTextReader Properties and Methods used in the GridView.

In order to make our grid persistent,  we've created a class called GridPersister that implements the functionality from the XmlTextReader and XmlTextWriter classes on our GridView.  Below is the UML design of our persistent GridView:



Figure 2 - UML Design of the Persistent GridView reverse engineered using the WithClass 2000.

In our example, we save all of our GridView information in an XML file including column names, column widths and cell information.  The way we store grid cells and their contents is similar to how HTML stores table information.  We nest the collection of column nodes inside a row node.  The column node contains the text, background color, and foreground color of the cell.  Below is a partial snapshot of the XML file we are going to create from the GridView shown in Figure 1.

 

Figure 3 - Snapshot of XML File created by the GridView Save Method.

Note that the XML file stores color information inside of attributes as aRGB numbers in integer format.  This is why you see these strange negative numbers after all of the color attributes.

Now let's see how we create this file using the GridPersister class.  Listing 1 below is the Write method inside of this class that produces the XML file shown in Figure 3.  The code first loops through the grids column headers and writes them out to the xml file.  Then it loops through rows and columns in the grid and writes out the nodes representing the contents of each cell of the grid.

Public Sub Write()
' Create instance of XmlTextWriter as a tool for writing our XML GridView information.
Dim writer As New XmlTextWriter(FilePath, Nothing)
' Indent the XML file to look nice.
writer.Formatting = Formatting.Indented
writer.Namespaces =
True
writer.Indentation = 4
' write header.
' Write the beginning header of our XML file along with a GridView tag.
writer.WriteStartDocument(False)
writer.WriteStartElement("GridView")
' write grid attributes column names and widths for our column headers.
writer.WriteStartElement("rowheader", Nothing)
Dim j As Integer
For j = 1 To m_GridView.NumberOfColumns
writer.WriteStartElement("colheader",
Nothing)
writer.WriteAttributeString("text", m_GridView.GetColumnName(j))
writer.WriteAttributeString("width", m_GridView.GetColumnWidth(j).ToString())
writer.WriteEndElement()
Next j
writer.WriteEndElement()
' write internal grid.
Dim i As Integer
For i = 0 To (m_GridView.NumberOfRows - 1) - 1
' write next row of grid as a node.
writer.WriteStartElement("row", Nothing)
' write each column node of grid including text, background color and foreground color.
Dim j As Integer
For j = 0 To m_GridView.NumberOfColumns - 1
writer.WriteStartElement("col",
Nothing)
writer.WriteAttributeString("text", m_GridView.GetCell(i + 1, j + 1))
writer.WriteAttributeString("backcolor", m_GridView.GetCellColor(i + 1, j + 1).ToArgb().ToString())
writer.WriteAttributeString("forecolor", m_GridView.GetCellTextColor(i + 1, j + 1).ToArgb().ToString())
writer.WriteEndElement()
Next j
writer.WriteEndElement()
Next i
writer.WriteEndElement()
writer.Flush()
writer.Close()
End Sub 'Write.

Listing 1 - Write method to write the XML file.

To read the file created by the Write method of the GridPersister we have created a Read method.  This is a bit more complex than the Write method because it needs to determine which node we are reading and extract the information.  The code for Reading the XML looks like a series of nested switch statements because as we read each  node, we need to parse the nested set of nodes inside.  Below is the code for reading the GridView XML information.

Public Sub Read()
Dim reader As New XmlTextReader(FilePath)
Dim rowCount As Integer = 0
Dim colCount As Integer = 0
Dim colHeaderCount As Integer = 0
Try
While reader.Read()
Select Case reader.NodeType
Case XmlNodeType.Element ' The node is the start of an Element.
Select Case reader.Name
Case "rowheader"
Case "colheader" ' Found the next column header, read the name and width.
colHeaderCount += 1
Dim i As Integer
For i = 0 To reader.AttributeCount - 1
' get the next attribute in the node and deterimine if its the column name or width.
reader.MoveToAttribute(i)
Select Case reader.Name
Case "text" ' set the next columnheader name to the attribute read.
m_GridView.SetColumnName(colHeaderCount, reader.Value)
Case "width" ' set the next columnheader width to the attribute red.
m_GridView.SetColumnWidthAndIgnoreFont(colHeaderCount, XmlConvert.ToInt32(reader.Value))
End Select
Next i
Case "row"
' current node is a row, increment the row count and reset the column count.
rowCount += 1
colCount = 0
Case "col"
' current node is a column, increment the column count.
colCount += 1
' Now set the cell for the current row and column, and read in the attributes for the cell.
Dim i As Integer
For i = 0 To reader.AttributeCount - 1
reader.MoveToAttribute(i)
Select Case reader.Name
Case "text"
' this attribute contains the text for the current cell, populate the cell in the gridview.
m_GridView.SetCell(rowCount, colCount, reader.Value)
Case "forecolor"
' this attribute contains the text color for the current cell, set the text color in the cell.
m_GridView.SetCellTextColor(rowCount, colCount, Color.FromArgb(Convert.ToInt32(reader.Value)))
Case "backcolor"
' this attribute contains the cell color for the current cell, set the color inside the cell.
m_GridView.SetCellColor(rowCount, colCount, Color.FromArgb(Convert.ToInt32(reader.Value)))
End Select
Next i
End Select
End Select
End While
Catch e As Exception
MessageBox.Show(e.Message.ToString())
End Try
End
Sub 'Read.

Listing 2 - Reading the XML GridView File.

The GridPersister Read and Write functionality is propagated through the GridView through the GridView's Open and Save methods.  Below is the code for Opening and Saving the GridView from a form:

Private Sub OpenMenu_Click(ByVal sender As Object, ByVal e As System.EventArgs)
gridView1.Open()
End Sub 'OpenMenu_Click

Listing 3 - Opening the GridView from a Windows Form

Private Sub menuItem2_Click(ByVal sender As Object, ByVal e As System.EventArgs)
gridView1.Save()
End Sub 'menuItem2_Click

Listing 4 - Saving the GridView from a Windows Form.

Summary.

This article demonstrated how to read and write the GridView to an XML file. The XML reading and writing functionality was accomplished using the XmlTextReader and XmlTextWriter classes. In the next article we will continue our journey with the GridView by describing how to send the GridView to the printer.  The final article in this series will show you how to extract a GridView into an Excel spreadsheet.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Mike Gold

Michael Gold is President of Microgold Software Inc., makers of the WithClass UML Tool. His company is a Microsoft VBA Partner and Borland Partner. Mike is a Microsoft MVP and founding member of C# Corner. He has a BSEE and MEng EE from Cornell University and has consulted for Chase Manhattan Bank, JP Morgan, Merrill Lynch, and Charles Schwab. Currently he is a senior developer at Finisar Corp. He has been involved in several .NET book projects, and is currently working on a book for using .NET with embedded systems.

He can be reached at mike@c-sharpcorner.com

Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the top 5 tips for understanding .NET
Ricky Leeks presents the top 5 tips for understanding .NET Interoperability. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
 Comments
updating multiple records in database using gridview by swathi On February 8, 2007
hii!!(in VB.NET) can i update at a time multiple records in database using gridview.???
Reply | Email | Modify 
Re: updating multiple records in database using gridview by Ibrahim On August 14, 2007

of course u can

but first modify your datagridview object as "Adding Records" then if u have used offline-connections with database and get the records to datagridview with dataset

use this method;

dataadapterobject.Update(datasetobject);

and it will update your records as u wish ;)

 

Reply | Email | Modify 
GridViewII by Karl On January 16, 2009
Thanks Mike for a great use of the ListView object. I'm bit of a n00b to VB 08 but I've altered your code to allow the first line to be edited.

The next stage is to allow a combo-box bound to a DB to appear in column 0. I'm happy to share the changed code, but not sure how to upload to this site :(

I changed the populate cell public procedure to allow rowNum > -1 like the columns and checked that the total number of items in the ListView was greater than 0.  This stops the out-of-range error you would have got just editing the rowNum to -1.

The start of it now looks like this:

        Sub PopulateCell(ByVal rowNum As Integer, ByVal colNum As Integer)

            If rowNum > -1 And colNum > -1 And listView1.Items.Count > 0 Then
Reply | Email | Modify 
Thanks a lot to suggest me this type of membership by Sushant On January 18, 2011
thank u sir
Reply | Email | Modify 
Discover the top 5 tips for understanding .NET Interop
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.