Click here to Skip to main content
Licence CPOL
First Posted 21 May 2008
Views 102,330
Downloads 1,877
Bookmarked 158 times

Extending the DataGridView

By | 23 Dec 2008 | Article
A few minor modifications to improve the DataGridView.
 
Part of The SQL Zone sponsored by
See Also

Introduction

The DataGridView is a powerful control, but there are some features missing. Some of these features include: a quick way to search through the data, ability to show/hide columns, export data, and keyboard shortcuts.

Searching

I wanted a Search feature which is very simple to use. I also wanted it to search as you typed. So, I took my inspiration from Firefox. A small bar at the bottom with one field to type in. The logic is quite simple. Search the sorted field for the text. To bring up the search, choose it from the header context menu, or press ` (above the Tab key).

Show/Hide Columns

When I display data to the user, there will quite often be advanced data that the user should be able to view, but hidden by default. So, with my control, you can simply click on the header to get the option to show and hide columns. If you don't want the user to be able to do this for a particular grid, simply use:

AllowAddRemoveColumns = false;

Export Data

A grid is much more useful if it can be exported into Excel. I have used the Microsoft Office 2003 Primary Interop Assemblies (must be installed on the client), which will import to Office 2003 and 2007. If it is not installed, the option will be changed to Export to CSV. A problem with Microsoft Office 2003 Primary Interop Assemblies is that Office must be installed to build the solution. To fix this, I use a fair bit of Reflection, but it is all in wrapper classes to keep the code neat.

This option can be found in the header's context menu.

Keyboard Shortcuts

The ability to sort and show/hide columns would be more useful to power users if they can do it from their keyboard. But I also want it to be intuitive. So, when you press the Control key the column numbers appear - these will be what we use for the shortcuts. Control + Column Number will sort on that column, and Control + Alt + Column Number will show/hide the column. The other important shortcut is, as mentioned above, the ` key (above the Tab, shift value is ~) for the Search.

Column Editor

This is a feature added in version 1.0.2. Perhaps the most annoying part of the normal DataGridView is it's column editor. Most of it is quite good. The problem is that the dialog is too small and you have to resize it. Then you close it, open it again and have to resize it again. It's only a small thing but it's the thing that annoys me more than anything in Visual Studio (and I'm not alone!). Since Microsoft hasn't fixed this (and may I point out it would take them less than 10 minutes to fix) I decided to fix it myself.

The Changes to the ExtendedDataGridView are minimal - You just require two attributes the first on the class of [DesignerAttribute(typeof(ExtendedDataGridViewDesigner))] and the second on the Columns property of [Editor(typeof(ExtendedDataGridViewColumnCollectionEditor), typeof(UITypeEditor))]. The classes these Attributes reference is where most of the work is done.

The ExtendedDataGridViewColumnCollectionEditor is the most important. The code is very similar (and based off of) the DataGridViewColumnCollectionEditor in System.Design. The main problem is that we require access to classes in that assembly which are marked as internal (the DataGridViewColumnCollectionDialog). So we must use reflection to get it. DataGridViewColumnCollectionDialog inherits from Form so when we get the object we will be working on it as a Form - which is all we need. We can easily set the MaximizeBox property to true and it's easy to get and set the Location and Size.

There is one further trick though, there is a small bug in DataGridViewColumnCollectionDialog. Normally it's hardly noticable but when we give it a larger initial size it's quite annoying. The problem is that it doesn't shrink from the initial size well. It grows well and shrinks to a size >= to the initial size well but when it gets smaller it acts like all controls are aligned to Top Right and Controls (Ok, Cancel and part of the Grid) are off screen. The easiest solution is to start with the form as small as possible and on the OnLoad set it to the Size we want.

And that's it! we have fixed the column editor! Well, almost. that fixes the Column Editor when you go to it from the Property Explorer. It doesn't fix it for when you click the thing on its top right coner and chose edit columns from the task pane. That's where ExtendedDataGridViewDesigner comes in. I won't go into much detail as it's mainly just copying the DataGridViewDesigner (from System.Design) code. Unfortunately I had to copy and not just inherit or use reflection to get most of the work done for me. But one advantage of this is if I want to add some of my own stuff to the task pane later I can.

So there we have it! A fully integrated improved Column Editor which is less annoying and should hopefully save you some time (even if it's just the time saved in not ranting about how annoying the size of the column editor is).

Other Features

How many times have you tried to figure out what the size of columns should be? The designer only lets you enter a number, see if it looks good, fix it up, check that out, and repeat until you are happy. On my control, if you press Shift while opening the header context menu, it displays the width next to each column. So, you can visually change the column width and then find out how wide it is.

Finally enums, my project includes a DataGridViewColumn for giving enums good descriptions. All you have to do is when you make an enum, declare it as follows...

public enum Example
{
    [Description("Enum Example 1")
    EnumEx1,
    [Description("Enum Example 2")
    EnumEx2,
}

History

  • Version 1 - Initial project.
  • Version 1.0.1 - Fixed a bug which stops some keyboard shortcuts from working when the header menu is still to be shown.
  • Version 1.0.2 - Project is now for Visual Studio 2008 (Sorry people on VS2005 but I don't have it installed anymore). The Column Editor now has a maximise button and remembers its location and size.

Final Thoughts

I would just like to thank everyone who has read this article and especially those who left feedback. I'm glad so many people have found it useful.

I noticed that some people rated it badly. I don't mind but if you do rate it badly please leave some feedback explaining why. Giving a bad rating doesn't improve an article. But leaving feedback explain why does.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Chris_McGrath

Software Developer (Senior)

Australia Australia

Member



Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralIssues with Visual Studio 2010 Pinmemberdelux2565:24 10 Jan '11  
Generalan improvement Pinmemberxisket14:01 19 Sep '10  
GeneralKewDown on Enter Pinmemberlalalav22:43 11 Jul '10  
QuestionSorting issue Pinmembergwired5:59 30 Dec '08  
AnswerRe: Sorting issue PinmemberChris_McGrath11:19 30 Dec '08  
GeneralCompile error [modified] PinmemberArielR23:45 29 Dec '08  
GeneralRe: Compile error PinmemberChris_McGrath11:03 30 Dec '08  
GeneralRe: Compile error PinmemberArielR0:47 31 Dec '08  
NewsAn update will happen soon. PinmemberChris_McGrath22:47 19 Dec '08  
NewsRe: An update will happen soon. PinmemberChris_McGrath13:06 20 Dec '08  
Questionnice article, but plz explain how can we do following Pinmembersairfan122:05 21 Nov '08  
AnswerRe: nice article, but plz explain how can we do following PinmemberChris_McGrath12:43 23 Nov '08  
Generalto make datgridview act as edit menu Pinmembermanojsakthikumar1:32 18 Jul '08  
GeneralRe: to make datgridview act as edit menu PinmemberChris_McGrath13:24 20 Jul '08  
GeneralSearch feature question Pinmemberajliaks22:03 30 Jun '08  
Generalsummarise perticular datagrid column( get sum of datagrid column data) Pinmemberayeshika7:56 27 Jun '08  
GeneralRe: summarise perticular datagrid column( get sum of datagrid column data) PinmemberChris_McGrath13:47 29 Jun '08  
It's a bit outside the scope of the article but I'll try and help. To me the sum is business logic and I would have a nice property in your business object which gives you the sum. But if you wanted to do it in the presentation logic, just loop through each row adding the values up. If you wanted you could extend my dgw and add a method called SumOfColumn pass in the column and put the logic there. Here's a quick go at it. I'm a C#er so forgive any mistakes in my VB.
 
public function SumOfColumn(col as DataGridViewColumn) as double
    dim sum as int = 0
    dim row as DataGridViewRow
 
    for each (row in Rows)
        sum += Convert.ToDouble(row.Cells(col.Name).Value);
    end for each
 
    return sum;
end function

QuestionWill it support Both IE and firefox? Pinmembersrinath g nath0:05 24 Jun '08  
AnswerRe: Will it support Both IE and firefox? PinmemberChris_McGrath13:23 24 Jun '08  
QuestionExcellent article Pinmemberajliaks6:24 22 Jun '08  
AnswerRe: Excellent article PinmemberChris_McGrath13:27 22 Jun '08  
GeneralRe: Excellent article Pinmemberajliaks19:50 22 Jun '08  
GeneralRe: Excellent article PinmemberChris_McGrath19:53 22 Jun '08  
GeneralHide / Show columns using keyboard Pinmemberajliaks3:04 23 Jun '08  
GeneralRe: Hide / Show columns using keyboard PinmemberChris_McGrath13:46 23 Jun '08  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web01 | 2.5.120529.1 | Last Updated 23 Dec 2008
Article Copyright 2008 by Chris_McGrath
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid