|
|
|
|
|
Home
»
VB.NET
»
An editable GridView Control in VB.NET
|
|
|
Author Rank:
|
|
Total page views :
60075
|
|
Total downloads :
1032
|
|
|
|
|
Download
Files:
|
|
|
|
|
|
|
|
|
|
|
|
|
Similar ArticlesMost ReadTop RatedLatest
|
|
|
|
|
|
|
|
|
|
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.
|
|
|
Login
to add your contents and source code to this article
|
|
|
|
|
|
|
|
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
|
|
|
|
|
|
|
|
|
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.
|
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
|
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today. With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications. Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
|
60 FREE UI Controls from DevExpress
Register for your FREE copy on over 60 free presentation controls from
DevExpress - Absolutely Free-of-Charge without any royalties or distribution
costs. Visit Devexpress.com/60 today. Free controls include advanced lists box, dropdown calendar, rich text edit, spin
edit, tab control and so much more!
DevExpress engineers feature rich presentation controls and reporting tools for WinForms, ASP.NET, WPF, and Silverlight. Our technologies help you build your best, see complex software with greater clarity and deliver compelling business solutions for Windows and the web in the shortest possible time.
|
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or
application via a range of API's. Learn More about our API connections.
|
Microsoft Visual Studio 2010
Visualize your workspace with new multiple monitor support, powerful Web development, new SharePoint support with tons of templates and Web parts, and more accurate targeting of any version of the .NET Framework. Get set to unleash your creativity.
|
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.
|
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
|
|
|
|
|
|
|
|
|
|
|
|
|