Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Blogs | Beginners
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » VB.NET » Customizing Datagrid Columns in Window Application

Customizing Datagrid Columns in Window Application


This article explains about how to customize the datagrid in window application using vb.net

Total page views :  31680
Total downloads : 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Become a Sponsor

Introduction:

 

The datagrid control in the window application can be easily customized as been done in web applications. The thing is datagrid in web can be designed using HTML tags and the same can be done in the window using the DataGridTableStyle namespace. The following example with the source code will explain clearly to achieve the same.

 

The following steps create an application showing the Northwind Products table in a DataGrid.

 

  1. On the File menu, select New, and then select Projects to create a new Windows Application project. Name the project CustomDataGrid.

  1. From the Toolbox, drag a DataGrid onto the displayed Form. Size it to generally fill the Form, and set its Anchor property to all four sides. The anchored Form in Visual Studio should look similar to Figure 1.

        

 

         Figure 1:

 

  1. Next, from the View menu, select the Server Explorer Window. Under Data Connections, open the Northwind node from the Tables list. Drag the Products table onto your Form on the Design Surface. After doing so, two components should display in the Components tray at the bottom of the Design Surface, an SqlConnection1 and an SqlDataAdapter1, as shown in Figure 2

        

 

         Figure 2:

 

  1. Right-click the SqlDataAdapter1 component and select Generate DataSet. The Generate DataSet dialog box appears, as shown in Figure 3. Press ENTER to accept the default action, which is to create a typed dataset, and place an instance of this dataset into your Component tray. 

         

         

    Figure 3:

   5.  On the Design Surface, click the DataGrid, and then on its property grid, set

        the  DataSource property to DataSet11Products

 

  1. Add a Form Load event handler by double-clicking an empty spot on the Form. In this event handler, type the following single line of code:  

        Me.SqlDataAdapter1.Fill(Me.DataSet11)

 

  1. Finally, compile and run your project. The grid should appear as illustrated in Figure 4.

Figure 4:

Customizing the Grid: Columns and Column Order

 

For the DataGrid, both the columns that appear in the DataGrid need to be controlled, as well as the order of their appearance. The columns and column order of the default DataGrid produced by the Designer is determined by the SQL Query generated as part of creating the SqlDataAdapter. From the default DataGrid, it is necessary to remove both the "SupplierID" and the "CategoryID". Also, the "Discontinued" column must be moved so that it is the very first column in the DataGrid instead of the last column.

 

It is possible to go back and manually adjust this SQL Query to control, which columns would appear in the DataGrid, and their order of appearance. But instead, the following demonstrates how to add a DataGridTableStyle to the DataGrid.

 

Once the DataGridTableStyle is added, it is possible to control which columns appear in the DataGrid, and their order of appearance by which DataGridColumnStyles are added to the DataGridTableStyle GridColumnStyles collection. The GridColumnStyles used by the DataGrid are determined at the point the DataGridTableStyle is added to the DataGrid.TableStyle collection. If the TableStyle.GridColumnStyle has not been populated with this collection by this point, a default set of ColumnStyles is created and used by the DataGrid. However, if DataGridColumns are specifically added to a DataGridTableStyle before adding the DataGridTableStyle to the DataGrid.TableStyles collection, then the columns that appear in the DataGrid are exactly those in the specified DataGridTableStyle.GridColumnStyles collection, and the column order will be the same as the order in the DataGridTableStyle.GridColumnStyles collection.

 

Before examining the code snippets that set the columns and column order, first look at the DataGridColumnStyle class. This is an abstract class. Normally, either the DataGridTextBoxColumn or the DataGridBoolColumn classes (the two DataGridColumnStyle derived classes shipped with the .NET Framework) are used. The main purpose of these classes is to control the appearance of a column in the DataGrid. For example, the DataGridBoolColumn makes the column look and behave like a check box.

 

The correspondence between a particular column in a DataTable, and a particular DataGridColumnStyle object is made through the DataGridColumnStyle.MappingName property. This property is the one required property that is needed to be set when creating a DataGridColumnStyle. Other DataGridColumnStyle properties of interest include Header, ReadOnly and Width.

 

The default DataGrid has the following ten columns in this order: ProductID, ProductName, SupplierID, CategoryID, QuantityPerUnit, UnitPrice, UnitsInStock, UnitsOnOrder, ReorderLevel and Discontinued. In the customized DataGrid, only eight columns are necessary in the following order: Discontinued, PrdID, PrdNAme, Quantity, Price, Stock, Order and Reord

 

The following is a modified Form Load event handler that will create the DataGridTableStyle (step 1), create the DataGridColumnStyles and add them to the GridColumnStyles collection (step 2), and finally, add the DataGridTableStyle to the DataGrid.TableStyles property (step 3).

 

Private Sub Form1_Load(ByVal sender As System.Object, _

            ByVal e As System.EventArgs) Handles MyBase.Load

    Me.SqlDataAdapter1.Fill(Me.DataSet11)

 

    'Step 1: Create a DataGridTableStyle

    '        set mappingname to table.

 

    Dim tblstyle As New DataGridTableStyle()

 

    tblstyle .MappingName = "PRODUCT"

 

    'Step 2: Create DataGridColumnStyle for each col

 

    '        we want to see in the grid and in the

    '        order that we want to see them.

 

    'Discontinued.

 

    Dim discontinuedCol As New DataGridBoolColumn()

    discontinuedCol.MappingName = "Discontinued"

    discontinuedCol.HeaderText = ""

    discontinuedCol.Width = 30

    'turn off tristate

 

    discontinuedCol.AllowNull = False

    tblstyle .GridColumnStyles.Add(discontinuedCol)

 

    'Step 2: PrdID

 

    Dim column As New DataGridTextBoxColumn()

    column.MappingName = "PrdID"

    column.HeaderText = "ID"

    column.Width = 30

    tblstyle .GridColumnStyles.Add(column)

 

    'Step 2: PRdNAme

 

    column = New DataGridTextBoxColumn()

    column.MappingName = "PRdNAme"

    column.HeaderText = "Name"

    column.Width = 140

    tblstyle .GridColumnStyles.Add(column)

 

    'Step 2: Qty

 

    column = New DataGridTextBoxColumn()

    column.MappingName = "Qty"

    column.HeaderText = "QuantityPerUnit"

    tblstyle .GridColumnStyles.Add(column)

 

    'Step 2: Price

 

    column = New DataGridTextBoxColumn()

    column.MappingName = "Price"

    column.HeaderText = "UnitPrice"

    tblstyle .GridColumnStyles.Add(column)

 

    'Step 2: Stock

 

    column = New DataGridTextBoxColumn()

    column.MappingName = "Stock"

    column.HeaderText = "UnitsInStock"

    tblstyle .GridColumnStyles.Add(column)

 

    'Step 2: Order

 

    column = New DataGridTextBoxColumn()

    column.MappingName = "Order"

    column.HeaderText = "UnitsOnOrder"

    tblstyle .GridColumnStyles.Add(column)

 

    'Step 2: Record

 

    column = New DataGridTextBoxColumn()

    column.MappingName = "Record"

    column.HeaderText = "ReorderLevel"

    tblstyle .GridColumnStyles.Add(column)

 

    'Step 3: Add the tablestyles and all  to the datagrid

 

    Me.DataGrid1.TableStyles.Add(tableStyle)

 

End Sub

Figure 5 is the DataGrid after adding the previous code. The columns should be exactly the columns previously specified as needed, and the Discontinued column should appear first.

 

Figure 5:

 

Conclusion:

 

There are so many customization of the datagrid in the window application and one among the customization is listed above. In the next article some more customizations will be explained.


Login to add your contents and source code to this article
 Article Extensions
Contents added by Raimundo Silva on Jun 24, 2009
 About the author
 
Sridhar Manoharan
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.
SQL and .NET performance profiling in one place
Investigate SQL and .NET code side-by-side with ANTS Performance Profiler 6, so you can see which is causing the problem without switching tools.
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.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
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
Read the Top 10 Books for Microsoft Developers, 15 Days FREE
Read the Top 10 Books for Microsoft Developers, 15 Days FREE
Try Safari Books Online - 15 Days FREE + 15% Off for 1 Year
Try Safari Books Online - 15 Days FREE + 15% Off for 1 Year
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
ASP.Net 4 Hosting is here
Become a Sponsor
 Comments
question by mah On August 27, 2007
how can i make events for check boxes in the dategrid cells
Reply | Email | Delete | Modify | 
datagrid by Shirley On December 3, 2007
When I add more than one DataGridViewButtonColumn in a static Data Grid the Order gets automatically rearranged and the Columns with this property appears first and the other colums are pushed after that. How to override this default ordering
Reply | Email | Delete | Modify | 
question by ayushman On December 15, 2007
Hi How can we add whole column suppose we are using a price as a new column and we want to add whole column then what type of coding we have to do
Reply | Email | Delete | Modify | 
newbie by trixdhy On March 7, 2008
hii. salam kenal ya.... mr.. article'na berguna banget buat saya soalnya di vb 6 tree view or list yang gampang di add checkbox....jdi saya mo blajar vb.net juga nich...
Reply | Email | Delete | Modify | 
Datagridview by Charlie On July 30, 2010
Hi Sir,
         Is this possible in Datagridview too?
Reply | Email | Delete | Modify | 
ANTS Performance Profiler 6.0
 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2010.8.14
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.