ARTICLE

Customizing Datagrid Columns in Window Application

Posted by Sridhar Manoharan Articles | Visual Basic 2010 September 24, 2007
This article explains about how to customize the datagrid in window application using vb.net
 
Reader Level:

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
share this article :
post comment
 

Hello Mr Manoharan, How are i hope that everything is allright. Anyway i need your help , and i wil be you if we make a deel about the price. I need to build in visualbasic 2008 a complete a billing system , invoice , creditors , and debitors , also rapport for uitstanding , grosse selles and statisic rapport. If you have any tutorials or books , or you can help througt a training , let me know , and of course i will pay you. MY MAIL IS naser_wahby@yahoo.com BEST REGARDS NASSER

Posted by naser wahby Mar 22, 2011

Hi Sir,
         Is this possible in Datagridview too?

Posted by Charlie Pandacan Jul 30, 2010

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...

Posted by trixdhy stuart Mar 07, 2008

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

Posted by ayushman bhagat Dec 15, 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

Posted by Shirley Dec 03, 2007
Nevron Diagram
Become a Sponsor
PREMIUM SPONSORS
  • 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.
    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. Visit DynamicPDF here
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor