Introduction

Visual Studio .NET comes with an out-of-the-box grid control called DataGrid. Complete with data-binding and many nifty features, it seems like a handy control. However, once you start using it, you may find that its usage is somewhat cumbersome and - in many real-life situations - downright puzzling. This article attempts to lead the beginner through the ropes of using DataGrid, including:

Data binding complex DataSets and OO class hierarchies

Adjusting columns and various "style" issues

Building usable context menus which behave according to position

Refreshing data updated outside of the grid code

Test Case

DataGrid is extremely easy to use when addressing a single table. Its navigation abilities give a very sexy (although I tend to be a skeptic regarding usefulness) view of table relations. In order to avoid the obvious, I designed a simple yet realistic domain with structure and requirements that do not fit the simple binding abilities of DataGrid. I call this domain Cars and I will use it for examples throughout this article:

A Car has 3 attributes: licensePlate, carType and price

A CarType has 2 attributes: name and manufacturer

A Manufacturer has a name

This domain can be found in the attached ZIP in 3 forms:

A Jet Database (Cars.mdb)

An XML schema (ObjectCars\CarDataSet.xsd)

A set of class files (ObjectCars\Car.vb,CarType.vb, CarManufacturer.vb)

The requirement is simple: write a grid-like screen to manage car prices. A snapshot was given above.

Data Binding

Why does DataGrid binding fall short? DataGrid defines its DataSource as a single IList, be it DataTable or object Array (multiple tables will create a "navigate" interface). While it is easy to infer all data relevant for a car by walking through relations/references, DataGrid column binding does not support a "dot" notation. In other words, when binding to a list of Cars, I can display Car.licensePlate, but not Car.carType.name. Let us walk through 3 possible solutions, each with its pros and cons.

Join Based DataBinding

When it comes to data querying, there is nothing easier or more maintainable than using SQL. A simple SQL join statement can feed the relevant data into a DataTable fashioned for our use. Pros: fast, easy, simple and maintainable. Don't stop reading here, because there are several flaws…

While you easily got the data to display, updating is now a major hassle: you need to "break" back into the original table structure before you can update your data base

In the 3-tier scenario there is something inherently wrong with requesting the server for data structured specifically for your screen. In cases where you don't own the server it is not only wrong, it is impossible.

The inherent data redundancy typical to a join (the same data exists in many rows) is error-prone when it comes to row creation.

An example of this approach can be found in the attached ZIP: SingleQueryCars\SQLJoinBasedForm.vb.

Multiple Table Based DataBinding

Microsoft tutorials emphasize the DataSet ability to store complex table structures allowing higher client independence and fewer round trips. Once we embrace this philosophy, we are required to join the tables on the client side: no SQL. Unfortunately, .NET does not include a Joiner utility class, so we need to join data in our code. The procedure is quite simple:

Essentially this is the same as what we did in an SQL join. The main benefit is client/server de-coupling, i.e. no server coding for grid purposes. The biggest drawbacks are client-side performance and additional procedural code. An example of this approach can be found in the attached ZIP: JoinBasedCars\LoopBasedJoinForm.vb.

Object List Data Binding

In many cases, it is best to leave DataSets as a link to the underlying DB and perform data manipulation using a class hierarchy (a.k.a. an "Object Domain"). The more logic in your application, the better this approach will serve you. Furthermore, in some cases Object Models are all we have. An example is when our server insists on handing data in Object form. Since "dot notation" is not supported, how can we display properties of anything but our "root objects" (i.e. cars)?

The solution is simple, although it may seem cumbersome at first: we create a new class (usually referred to as the "viewer" class), which wraps the root object and exports all needed data as properties. For instance, in our example we would code a CarViewer class wrapping a Car object and exporting the properties licensePlate, typeName and manufacturerName. We would then bind an ArrayList of these to the DataGrid.

It turns out that this solution is extremely powerful, since it gives us a natural place for a user-interface related code that is non-trivial: things like calculated attributes, complex use cases (how about "switch plates with another car"), etc. In fact, it usually makes sense to use viewer-based grids instead of performing "procedural joins," even if you have the data in a DataSet and not an Object Domain.

Not surprisingly, the author did not invent this concept. It is an adaptation of a well-known paradigm called MVC (Model-View-Controller) and you are welcome to read any of the multitudes of excellent articles available on the Internet. An example of this approach can be found in the attached ZIP: ObjectCars\ViewerBasedForm.vb.

Refreshing the Grid

No matter how you perform data binding, if your application views dynamic data you are bound to refresh the grid at some time. It turns out that this is another trivial task that was made "un-obvious." Here's how:

Get the DataGridCurrencyManager

Call its refresh method

Note the parameter to BindingContext. This is where most people fail. It should be a reference to the exact object you bound.

Formatting the Grid

Now that we have all relevant data bound, it's a good idea to make it human-readable. Grid formatting is relatively easy, but from the amount of discussion devoted to it in news groups, one can infer that Microsoft did not expose it very neatly. I will try to sort the basics and give some pointers to more advanced stuff.

Basic Column Formatting

All grid formatting is centered about the TableStyles collection accessible via the grid property window. Here is how it works:

A style defines most of the grid formatting properties, including column format (via a collection called GridColumnStyles)

At any given moment, the grid adheres to one style selected according to the style MappingName property

Once you understand this, many of the basic tasks are, well, basic. Here are some examples:

Column caption, width, Read/Write, control type (text box / check box) and more are defined in the column style

Column order is determined by GridColumnStyle order

If we want to "hide" a column, we don't map it to any column style

The only trick left is to determine the right mapping name:

When grid shows a DataSetDataTable, use the table name as defined in the schema

Examples for this can be found in all 3 forms supplied in the attached ZIP. Of course, all these properties are accessible at runtime, allowing easy implementation of features such as "re-arrange columns," "hide column," etc.

Advanced Formatting

Unfortunately, some extremely useful features we expect of a DataGrid are not easily implemented and require more advanced programming. Chief among these are:

The ability to use controls other than text box and check box

The ability to dynamically control colors and fonts at cell level

Once we understand that the heart of formatting is the DataGridColumn class, then it is evident that to achieve advanced formatting we need to extend it in a manner that fits us. Excellent pointers for such work can be found here (combo in grid).

Context Menus

In real life applications, grids will usually have more than one context menu: column header menu will differ from cell menu; row header menu might differ from both and sometimes the menu may be affected by selection areas. Although DataGrid has only one ContextMenu, managing this kind of behavior is simple enough:

Create all needed menus, either on the designer or dynamically

Write a handler for the DataGrid.MouseDown event:

Check for right-click

Compute the row/column clicked

Set the DataGrid.ContextMenu according to context

Note that this works since your handler is called before the context menu is displayed. Here is an example that shows a context menu only when clicked over a cell. It stores cell coordinates for later use by the context menu handlers:

The Attached Source Code

SingleQueryCars is a read-only grid based on an SQL join; it mainly shows column customization.

JoinBasedCars has similar functionality, but it also exemplifies client side join of several DataSet tables

ObjectCars is a bit more interesting (as I believe this is the best way most of the time); it demonstrates all discussed and a bit more, including:

Simple mapping a data set to an object domain

Viewer management

Column formatting

Context menu usage

Adding lines, deleting lines, hiding lines

Summary

There are already several .NET grids on the market which look much better than DataGrid and more will come. However, when used correctly, DataGrid can still take you a long way to a usable user interface and it is certainly worth your while experimenting with it further.

Share

About the Author

Omri started coding way back in the good ol' Apple ][ days. His first commercial (acutally governmental) software package was released 1986.
In the 90's Omri programmed C and C++, and managed larger development teams using MFC/COM.
In the last 3 years he is into Java server programming, and while he loves the language and community, he has many reservations. Maybe this is why .Net feels like comming back home...

Comments and Discussions

My application having one mdiform in that form six child forms are there.Switching of one form into anather form blur bars are appearing form at the title of every opened child form.These six child forms are opens in mdiform.how to remove the blue bars are appearing from every opened child form in mdiform.how to remove these blue bar.To avoid that issue please help me.

How am i access the data from dataGride in Vb.net.
that is say i have a datagrid which contain some row and column and all column contains the data,
now i want to update the data of any column in datagrid when i select of another column value. how i solve this problem please send me my email address this solving code.

I have a calculated field called 'Total' that is the sum of other fields (12 months) that I want to update any time a value is changed in one of the months and without updating the data. Does someone know how to do that?

Public Function ReturnDS(ByVal strsql As String, ByVal strTable As String) As DataSet
Try

Dim oDataAdapter As New OleDb.OleDbDataAdapter(strsql, oConnection)
Dim oDataSet As New DataSet
oDataAdapter.Fill(oDataSet, strTable)

Return oDataSet

Catch ex As Exception
Throw New Exception(ex.Message)
End Try
End Function

-----------------------------------------------------------------------------------------------------
The following method populates the data from the database int to the datagrid
using a dataset.......[ mydataset ].

I have put a data grid on my form and provided data to it. However, in order to see the data I must expand it then click the FieldNames option in the grid. Once I do this the data is displayed correctly even after I change the data source. Any suggestions, I have added a call to the Expand Method but I still have to click the FieldNames option.

I have created a Structure Customers which has fields like custname,custaddress etc...I have filled the structure with the records from the database..Now how can i attach the structure to the datagrid??

I am using a datagrid on my Windows form to display records stored in a SQL Server database. When the form loads the datagrid is populated with the records. When I select an item in the datagrid the values are displayed in some text boxes. So when i select a different row in the datagrid the text boxes change accordingly. This part is fine.

I then have two buttons, Add and Delete. I use SQL statements to Add and Delete records. The SQL statements are fine and when I check the table in SQL Server the Addition or Deletion has been successful. The problem is refreshing my datagrid. If i close the form and open it again the datagrid reflects the changes, but i want it to refresh without closing and opening the form. The code for the Add button is as follows:

I have a datagrid with a combobox column style
and i have these problems
1- I want to enter a value that is in combo if the value which has entered is wrong I want the focus still in combo
to correct the typed value
2- I have a column which is hidden and its required to databse and i add a value to it by code
when I go to the second row to the combo box which is the first column not hidden a message appear like this
the column ... does not allow null do you want to correct the value
Can I get any help

I have a datagrid as a detail for a master records
in the master I have a primary key and in the detail I have created the primary which is the field from the master table and the and another field which I want it autoincrement depened on the first field
for example if i have a , b are the primary
if a=1 then I want b is (1,2,3,4...)
and if a=2 I want B also is (1,2,3,....)
after that I can make a and b hidden columns in datagrid
the user enter the others fields and he is not need to concern with the a and b
Can I get an help with my regards.

I need to check if a item e.q. a telefonenumber has already been used for an other relation. If this is the case The user should got a msgBox and got the choice if he wants to swap the telefone number yes or no.
The telefonenumbers appear in a datagrid (many numbers, one relation e.g. a compagny) Wich events do I need? I spend a whole lot of time yet searching for the right one..
Is there anybody out there who could help me...

Your OO Viewer wrap is fantastic! However, it does not sort the column display according to the SELECT statement as in a normal datagrid. Can I choose which columns in the viewer that I want to display (similar to DataGridTextBoxColumn)?