Customizing the Windows Forms DataGrid
Dr. Clay Burch, .NET MVP
Microsoft® Visual Studio® .NET
Summary: The following demonstrates how easy it is to use the Windows Forms DataGrid in Microsoft Visual Studio .NET for basic display of tabular data on a form. In addition, a demonstration on how to customize the DataGrid's default behavior is included, allowing you more flexibility in how you can use the DataGrid. (24 printed pages)
Download the sample code file datagridcustomization.exe in the Microsoft Download Center.
Customizing the Grid
The following discussion steps you through customizing the look and functionality of a Windows Forms DataGrid. A DataGridBoolColumn is derived that exposes a BoolValChanged event that is raised anytime the checkbox value changes. Also derived is a DataGridTextBoxColumn that exposes a CellFormatting event that allows control of the cell's Font, ForeColor and BackColor on a cell-by-cell basis. The DataGrid's CurrentCellChanged event is used to force the focus to go to a particular column, no matter which column was initially clicked in a row. Also shown is how to dynamically change the appearance of cells in a DataGrid, depending upon the value of key cells. Here, a key cell is a cell whose value determines the appearance of other cells. Further demonstrated is how to make a check box column react to the initial click in the cell to change its checked state and how to control which columns appear in the DataGrid, as well as their order, independent of how the columns occur in the underlying DataSource. Finally, it is demonstrated how to use the Windows Forms ToolTip control to display tips that vary row-by-row in the DataGrid. In short, a DataGrid should look as the one in Figure 1:
Figure 1 The Customized DataGrid
The following contains a goal that is two-fold. The first goal is to show how easy it is to use the Windows Forms DataGrid for basic display of tabular data on a form. The second goal is to demonstrate how to customize the DataGrid's default behavior, allowing more flexibility in how to use the DataGrid. In doing so, it is demonstrated how to create classes that can be used in projects to enable similar functionality in applications.
If using the Designer to display a DataGrid using a DataTable is a familiar practice, skip ahead to the section titled Customizing the Grid. The following examples use VB .NET to show code snippets. The code samples include both VB .NET and C# sample projects.
Start out by creating a Windows Forms Application in Visual Studio .NET, dropping a DataGrid onto the Form, and adding a DataSource. Do all of this from the Designer. To bring up and display a DataGrid bound to an ADO.NET data source, exactly one line of code is written. To allow users to edit the displayed values and save them back to the data source, a second line of code is written. This discussion assumes that the DataBase Samples that ship with the .NET Framework are installed. If not, you can do so from this link (change the hard disk drive location, depending on your Visual Studio .NET install location):
C:\Program Files\Microsoft Visual Studio.NET\FrameworkSDK\Samples\StartSamples.htm
The following steps create an application showing the Northwind Products table in a DataGrid.
On the File menu, select New, and then select Projects to create a new Windows Application project. Name the project CustomDataGrid.
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 2.
Figure 2 The Anchored Form in Visual Studio
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, a SqlConnection1 and a SqlDataAdapter1, as shown in Figure 3.
Figure 3 Form with SqlConnection and SqlDataAdapter Components
Right-click the SqlDataAdapter1 component and select Generate DataSet. The Generate DataSet dialog box appears, as shown in Figure 4. 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 4 Generating the DataSet
On the Design Surface, click the DataGrid, and then on its property grid, set the DataSource property to DataSet11Products.
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:
Finally, compile and run your project. The grid should appear as illustrated in Figure 5.
Figure 5 The DataGrid Produced with the Designer and One Line of Code
Customizing the Grid
Customization 1: 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. Later in the discussion, more is derived from these two classes to further customize the appearance and behavior of the columns.
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, ProductID, ProductName, QuantityPerUnit, UnitPrice, UnitsInStock, UnitsOnOrder and ReorderLevel.
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 tableStyle As New DataGridTableStyle() tableStyle.MappingName = "Products" '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 tableStyle.GridColumnStyles.Add(discontinuedCol) 'Step 2: ProductID Dim column As New DataGridTextBoxColumn() column.MappingName = "ProductID" column.HeaderText = "ID" column.Width = 30 tableStyle.GridColumnStyles.Add(column) 'Step 2: ProductName column = New DataGridTextBoxColumn() column.MappingName = "ProductName" column.HeaderText = "Name" column.Width = 140 tableStyle.GridColumnStyles.Add(column) 'Step 2: QuantityPerUnit column = New DataGridTextBoxColumn() column.MappingName = "QuantityPerUnit" column.HeaderText = "QuantityPerUnit" tableStyle.GridColumnStyles.Add(column) 'Step 2: UnitPrice column = New DataGridTextBoxColumn() column.MappingName = "UnitPrice" column.HeaderText = "UnitPrice" tableStyle.GridColumnStyles.Add(column) 'Step 2: UnitsInStock column = New DataGridTextBoxColumn() column.MappingName = "UnitsInStock" column.HeaderText = "UnitsInStock" tableStyle.GridColumnStyles.Add(column) 'Step 2: UnitsOnOrder column = New DataGridTextBoxColumn() column.MappingName = "UnitsOnOrder" column.HeaderText = "UnitsOnOrder" tableStyle.GridColumnStyles.Add(column) 'Step 2: ReorderLevel column = New DataGridTextBoxColumn() column.MappingName = "ReorderLevel" column.HeaderText = "ReorderLevel" tableStyle.GridColumnStyles.Add(column) 'Step 3: Add the tablestyle to the datagrid Me.DataGrid1.TableStyles.Add(tableStyle) End Sub
Figure 6 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 6 DataGrid Showing Specific Columns in a Specific Order
Customization 2: Change Click Behavior on a Discontinued Row
In the following example, say that for a Discontinued product, the user should be unable to edit any cell in that row unless the user first removes the Discontinued check mark. Therefore, when the user clicks in any cell in a Discontinued row, instead of that cell getting focus, the focus shifts to the first column, Discontinued.
To handle this requirement, add a handler for the CurrentCellChanged event. In that handler, if the value in the Discontinued column in the current row is true, directly set the current cell to the Discontinued column. See the following code example:
Private Sub dataGrid1_CurrentCellChanged( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles DataGrid1.CurrentCellChanged 'if click on a discontinued row, then set currentcell to checkbox Dim discontinuedColumn As Integer = 0 Dim val As Object = Me.DataGrid1( _ Me.DataGrid1.CurrentRowIndex, _ discontinuedColumn) Dim productDiscontinued As Boolean = CBool(val) If productDiscontinued Then Me.DataGrid1.CurrentCell = _ New DataGridCell( _ Me.DataGrid1.CurrentRowIndex, _ discontinuedColumn) End If End Sub
Customization 3: Make the Check Box Respond to One Click
In a DataGrid with a check box column, the default behavior requires two clicks to actually change the checked value. The first click sets focus to the cell, and the second click will change the checked state. To modify this behavior for this example, make the checked value change on the first click. Handle this by listening to the DataGrid.Click event, and checking for a hit in the check box cell. If it is the first click after the cell becomes current, explicitly change the Boolean value in the grid. To track the first click after the cell becomes current, add a variable to the form, and set it in the existing CurrentCellChanged handler.
The following are the code snippets that implement this one-click behavior. In the Click handler, take the mouse position and pass it to the DataGrid's HitTest method in order to decide which cell is clicked. The goal is to act on the first click in the check box cell after the current cell has changed. There is also a check to avoid a problem that occurs when the AddNew row is clicked that appears at the bottom of the DataGrid. This check involves making sure the row that is clicked is a real row that is bound to the datasource. Do this by comparing the clicked row to the Count property of the BindingManagerBase.
Private afterCurrentCellChanged As Boolean = False Private Sub dataGrid1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles DataGrid1.Click Dim discontinuedColumn As Integer = 0 Dim pt As Point = Me.dataGrid1.PointToClient( _ Control.MousePosition) Dim hti As DataGrid.HitTestInfo = _ Me.dataGrid1.HitTest(pt) Dim bmb As BindingManagerBase = _ Me.BindingContext(Me.dataGrid1.DataSource, _ Me.dataGrid1.DataMember) If afterCurrentCellChanged _ AndAlso hti.Row < bmb.Count _ AndAlso hti.Type = DataGrid.HitTestType.Cell _ AndAlso hti.Column = discontinuedColumn Then Me.DataGrid1(hti.Row, discontinuedColumn) = _ Not CBool(Me.DataGrid1(hti.Row, _ discontinuedColumn)) End If afterCurrentCellChanged = False End Sub 'dataGrid1_Click 'add a line to this existing handler Private Sub dataGrid1_CurrentCellChanged( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles DataGrid1.CurrentCellChanged 'if click on a discontinued row, then set 'currentcell to checkbox Dim discontinuedColumn As Integer = 0 Dim val As Object = Me.DataGrid1( _ Me.DataGrid1.CurrentRowIndex, _ discontinuedColumn) Dim productDiscontinued As Boolean = CBool(val) If productDiscontinued Then Me.DataGrid1.CurrentCell = _ New DataGridCell( Me.DataGrid1.CurrentRowIndex, _ discontinuedColumn) End If 'add this line afterCurrentCellChanged = True End Sub 'dataGrid1_CurrentCellChanged
Customization 4: Changing Cell BackColor, ForeColor and Font
To customize the way a DataGrid cell is drawn, it is necessary to override the Paint method in a derived DataGridTextBoxColumn class. When the DataGrid with a DataGridTableStyle associated with it needs to paint a cell, it calls the Paint method of the DataGridTextBoxColumn. The arguments in this call include a ForeBrush and BackBrush that controls the colors used to draw the cell. Therefore, to control the colors used to paint a cell on a per cell basis, it is possible to override the virtual Paint method of the DataGridTextBoxColumn class, and change the brushes according to the particular cell being drawn.
The following strategy is to add an event to the derived DataGridTextBoxColumn. In the derived Paint method, this event is fired to allow listeners to provide the BackColor and ForeColor to be used for the cell being painted. Once this event is in place, it is only necessary to write an event handler to control the color of a grid cell. Also derived are special EventArgs to provide the event listener with the row index and column index values, and to allow the event listener to set the color properties.
Creating the Event Arguments Class
In Solution Explorer, right-click the project, and add a new class named DataGridFormatCellEventArgs, which is inherited from EventArgs. The following is a list of the public properties of this class and a note on how they are used. The first three properties are passed into the event handler through the argument; the last seven properties are set by the event listener to indicate how the cell should be drawn.
- Column (Integer): The column number of the cell being painted.
- Row (Integer): The row number of the cell being painted.
- CurrentCellValue (Object): The current cell value.
- TextFont (Font): The font to be used to draw text in the cell.
- BackBrush (Brush): The brush used to paint the cell's background.
- ForeBrush (Brush): The brush used to paint the text in the cell.
- TextFontDispose (Boolean): True to call the TextFont.Dispose.
- BackBrushDispose (Boolean): True to call the BackBrush.Dispose.
- ForeBrushDispose (Boolean): True to call the ForeBrush.Dispose.
- UseBaseClassDrawing (Boolean): True to call the MyBase.Paint.
The dispose properties included as part of the DataGridFormatCellEventArgs are set by the listener if the Paint override should call the Dispose method on the objects that implement IDisposable. For example, if dynamically creating a BackBrush every time a grid cell is drawn, use the Paint method to call Dispose on the brush after it is finished with its drawing. On the other hand, if a single brush is created and cached that will be used to provide the BackBrush for some cells, it is not desirable to have the Paint method to call Dispose on the cached brush. These dispose properties let the listener tell the Paint override how to handle the Dispose calls.
The following is how the actual class code should appear. Before the class definition, add the delegate that determines the signature of the event handler required for the SetCellFormat event that will be defined as part of the derived DataGridTextBoxColumn.
Public Delegate Sub FormatCellEventHandler( _ ByVal sender As Object, _ ByVal e As DataGridFormatCellEventArgs) Public Class DataGridFormatCellEventArgs Inherits EventArgs Public Sub New(ByVal row As Integer, _ ByVal col As Integer, _ ByVal cellValue As Object) End Sub 'New End Class
Creating the Derived DataGridTextBoxColumn
The next step is to add the class code for the derived DataGridTextBoxColumn. This is done in the same way, right-clicking the project in Solution Explorer and adding a new class named FormattableTextBoxColumn. To add the stub for the Paint override, select (Overrides) in the left drop-down list on top of the editing window, and then select the second Paint method (the one with seven arguments) listed in the right drop-down list at the top of the editing window. The following is what the code will look like.
Note Notice the SetCellFormat event declaration is also added, using the event delegate FormatCellEventHandler that was defined in the previous class file.
Public Class FormattableTextBoxColumn Inherits DataGridTextBoxColumn Public Event SetCellFormat As FormatCellEventHandler Protected Overloads Overrides Sub Paint(………) End Sub 'Paint End Class
Implementing the Paint Override
The first thing to do in the Paint override is to fire the SetCellFormat event. It is through this event that an event listener will provide the format preferences that are to be used with this cell. The steps are to create the DataGridFormatCellEventArgs, initializing the row, column and current value, and then raise the event with this argument. Finally, after the event has been raised, query the event argument to see what formatting actions need to be done.
Raising the Event
The following is the code snippet that creates the argument and fires the event. The variables source and rowNum are passed into the Paint method.
Dim e As DataGridFormatCellEventArgs = Nothing 'Get the column number Dim col As Integer = _ Me.DataGridTableStyle.GridColumnStyles.IndexOf(Me) 'Create the eventargs object e = New DataGridFormatCellEventArgs( _ rowNum, col, _ Me.GetColumnValueAtRow([source], rowNum)) 'fire the formatting event RaiseEvent SetCellFormat(Me, e)
Once the event has returned, inspect the properties of the DataGridFormatCellEventArgs object to find out about the colors in which the cell should appear. The two brushes, foreBrush and backBrush, used to draw the cell are passed as arguments to the Paint method. To change the cell colors, swap the old brushes for the new brushes before calling the Paint method's base class implementation. The following is a code snippet that illustrates this idea:
' assume we will call the baseclass Dim callBaseClass As Boolean = True ' check the brushes returned from the event If Not (e.BackBrush Is Nothing) Then backBrush = e.BackBrush End If If Not (e.ForeBrush Is Nothing) Then foreBrush = e.ForeBrush End If ' check the UseBaseClassDrawing property If Not e.UseBaseClassDrawing Then callBaseClass = False End If If callBaseClass Then MyBase.Paint(g, bounds, _ [source], rowNum, backBrush, _ foreBrush, alignToRight) End If
The previous snippet sets the brushes depending upon the properties of the DataGridFormatCellEventArgs object. Depending upon the UseBaseClassDrawing value, it calls the base class. Calling the base class with the modified brushes is how to affect the cell color. Recall that this method will be called for each cell in a column as it is drawn.
Handling the TextFont Property
Trying to change the font used to draw in the cell adds a real complication to the Paint override. The reason is that the font used to draw the text is not a simple parameter passed as an argument in the Paint method. Instead, the font used to draw the cell text is originally gotten from the DataGrid.Font property. But this font is cached, and is not reset from the DataGrid.Font property for each cell. Thus, the first impulse, dynamically changing DataGrid.Font for each cell does not work. Therefore, to change the font of the cell, it is necessary to actually draw the string so that the font can be specified. Doing so adds significant work to try to mimic exactly the output of the standard DataGrid. The example will not go to extremes in this respect, but will be satisfied to get similar output, but not exactly the same output as with the unaltered DataGrid. The following is the code snippet that is used to implement drawing the string with a newly specified font.
'if TextFont set, then must call drawstring If Not (e.TextFont Is Nothing) Then Try Dim charWidth As Integer = _ Fix(Math.Ceiling(g.MeasureString("c", _ e.TextFont, 20, _ StringFormat.GenericTypographic).Width)) Dim s As String = _ Me.GetColumnValueAtRow([source], _ rowNum).ToString() Dim maxChars As Integer = _ Math.Min(s.Length, bounds.Width / charWidth) Try g.FillRectangle(backBrush, bounds) g.DrawString(s.Substring(0, maxChars), _ e.TextFont, foreBrush, _ bounds.X, bounds.Y + 2) Catch ex As Exception Console.WriteLine(ex.Message.ToString()) End Try Catch 'empty catch End Try callBaseClass = False End If
The first part of the code approximates the number of characters that can be displayed in the current cell width. It does so by approximating an average character size, and dividing this value into the cell width. It would be possible to do this more rigorously—repeatedly calling MeasureString to get the exact number of characters that would fit—but doing so makes the output significantly different than what the default DataGrid produces. Using this average character size approach is much quicker, and gives results much closer to the default DataGrid.
After getting the number of characters, draw the background and call Graphics.DrawString passing it the font and brush desired for use. Finally, set the callBaseClass flag so the baseclass Paint method is not later called, undoing all of the previous work.
Using the New FormattableTextBoxColumn Class
To use the newly derived column, go back to the form code, and swap out the occurrences of DataGridTextBoxColumn with FormattableTextBoxColumn. Then for each column, wire up the listener for the SetCellFormat event exposed by the derived class. There exists the option of using a different event handler for each column. But the requirements (coloring rows) allow the use of the same handler for all the columns. The following is the code for the typical column after these changes:
'ProductName column = New FormattableTextBoxColumn() column.MappingName = "ProductName" column.HeaderText = "Name" column.Width = 140 AddHandler column.SetCellFormat, AddressOf FormatGridRow tableStyle.GridColumnStyles.Add(column)
Notice that an instance of a derived class is now being created, FormattableTextBoxColumn. Also, a handler is added, FormatGridRow, for the SetCellFormat event.
The SetCellFormat Event Handler
In the SetCellFormat handler, the brushes used to set the forecolor and backcolor of the cell whose row and column indexes are passed in through the event arguments will be set. If the cell is on the current row of the grid, use one set of colors and font. If the cell is on a row that has the Discontinued Boolean value set to true, use another set of colors. The following is the code that declares and defines these cached GDI+ objects.
'form variables to cache GDI+ objects Private disabledBackBrush As Brush Private disabledTextBrush As Brush Private currentRowFont As Font Private currentRowBackBrush As Brush ' In Form1_Load create and cache some GDI+ objects. Me.disabledBackBrush = _ New SolidBrush(SystemColors.InactiveCaptionText) Me.disabledTextBrush = _ New SolidBrush(SystemColors.GrayText) Me.currentRowFont = _ New Font(Me.DataGrid1.Font.Name, _ Me.DataGrid1.Font.Size, _ FontStyle.Bold) Me.currentRowBackBrush = Brushes.DodgerBlue
In the code for the event handler, members of the DataGridFormatCellEventArgs value that are passed to display particular rows with special effects will be set. Discontinued rows will be grayed out, and the current row will be displayed with a DodgerBlue background using a bold font. The following is the handler that will implement these effects:
Private Sub FormatGridRow(ByVal sender As Object, _ ByVal e As DataGridFormatCellEventArgs) Dim discontinuedColumn As Integer = 0 ' Conditionally set properties in e depending upon e.Row and e.Col. Dim discontinued As Boolean = CBool( _ IIf(e.Column <> discontinuedColumn, _ Me.DataGrid1(e.Row, discontinuedColumn), _ e.CurrentCellValue)) ' Check if discontinued? If e.Column > discontinuedColumn AndAlso _ CBool(Me.DataGrid1(e.Row, discontinuedColumn)) Then e.BackBrush = Me.disabledBackBrush e.ForeBrush = Me.disabledTextBrush ' current row? ElseIf e.Column > discontinuedColumn AndAlso _ e.Row = Me.DataGrid1.CurrentRowIndex Then e.BackBrush = Me.currentRowBackBrush e.TextFont = Me.currentRowFont End If End Sub
Recall that there are actually several FormattableTextBoxColumn objects in the DataGrid.TableStyle(0).GridColumnStyles collection. In fact, every column, except the Boolean column, is using one of these objects. In addition, each of these objects has a SetCellFormat event, to which is being listened. However, each of these events is using the same handler, FormatGridRow, which was previously listed. Thus, the same formatting logic is being applied to every cell (except the Boolean cell) in a row. Therefore, the formatting is effectively setting row styles in that all cells in the row will show the same formatting behavior, even though the formatting is being done on a cell-by-cell basis.
Take a Look
The following is a picture of the grid at this point. Notice that the checked rows are grayed out, showing the item is discontinued, and the current row is DodgerBlue with a bold font.
Figure 7 The DataGrid with Colored Rows
The initial display looks pretty good. But there is a small problem that needs some effort to handle. The problem is that a click on a checked first column unchecks the cell properly, but does not redraw the row. This row needs to be refreshed anytime the check value changes. To handle this problem, it is necessary to derive from DataGridBooleanColumn and add an event handler that fires an event anytime the bool value changes. This will allow reaction to the changing click, and forces the row to be redrawn reflecting the new click value.
Customization 5: Adding a Boolean Column with a Value Changed
The Event Arguments
Start by adding a new class derived from EventArgs that holds the information the BoolValueChanged event will require. In particular, properties will be added that give the row and column of the cell being changed, as well as add properties to the new Boolean value. The following is the BoolValueChangedEventArgs class. The missing implementation uses private fields only to shadow the public properties with the fields being initialized in the constructor. The delegate will also be defined, BoolValueChangedEventHandler, for this event at the beginning of this file.
Public Delegate Sub BoolValueChangedEventHandler( _ ByVal sender As Object, _ ByVal e As BoolValueChangedEventArgs) Public Class BoolValueChangedEventArgs Inherits EventArgs Public Sub New(ByVal row As Integer, _ ByVal col As Integer, _ ByVal val As Boolean) . . . End Sub 'New Public Property Column() As Integer . . . End Property Public Property Row() As Integer . . . End Property Public ReadOnly Property BoolValue() As Boolean . . . End Property End Class 'BoolValueChangedEventArgs
The Derived DataGridBoolColumn Class
Now for the derived class, ClickableBooleanColumn, three methods will be overridden to handle different aspects of monitoring the Boolean value in the cell. The first override is Edit. This method is called when a cell needs to go into edit mode. In the override, some private field members will be set to reflect the current Boolean state as well as the fact that the current mode is in edit mode. The second override is the same Paint method that was previously used in FormattableTextBoxColumn. Here, instead of trying to modify the cell appearance, this method is used to track the change in the Boolean value, and to raise the BoolValueChanged event if it does change. The third override is the Commit method. This method is called when the editing is complete, and the value should be committed to the datasource. This method is used to turn off the fields that were set in the Edit override.
There are some technical points that need to be handled. The Boolean value can change because of a click in the cell, or a pressed spacebar, while the cell has focus. The helper method, ManageBoolValueChanging, is used to monitor these possibilities. Furthermore, it raises the BoolValueChanged event if the value is changed. To monitor the mouse click, the ManageBoolValueChanging checks the Control.MousePosition and Control.MouseButtons shared (static) properties. However, checking the KeyState of the spacebar is problematic. Resort to an Interop call into Win32 API GetKeyState to handle this problem.
The following is the code for the class:
Public Class ClickableBooleanColumn Inherits DataGridBoolColumn 'changed event Public Event BoolValueChanged _ As BoolValueChangedEventHandler 'set variables to start tracking bool changes Protected Overloads Overrides Sub Edit(. . .) Me.lockValue = True Me.beingEdited = True Me.saveRow = rowNum Me.saveValue = CBool( _ MyBase.GetColumnValueAtRow( _ [source], rowNum)) MyBase.Edit(. . .) End Sub 'Edit 'overridden to handle BoolChange event Protected Overloads Overrides Sub Paint(. . .) Dim colNum As Integer = _ Me.DataGridTableStyle.GridColumnStyles.IndexOf(Me) 'used to handle the boolchanging ManageBoolValueChanging(rowNum, colNum) MyBase.Paint(. . .) End Sub 'Paint 'turn off tracking bool changes Protected Overrides Function Commit(. . .) As Boolean Me.lockValue = True Me.beingEdited = False Return MyBase.Commit(dataSource, rowNum) End Function 'Commit 'fields to track bool value Private saveValue As Boolean = False Private saveRow As Integer = -1 Private lockValue As Boolean = False Private beingEdited As Boolean = False Public Const VK_SPACE As Integer = 32 'needed to get the space bar changing of the bool value <System.Runtime.InteropServices.DllImport("user32.dll")> _ Shared Function GetKeyState( _ ByVal nVirtKey As Integer) As Short End Function 'fire the bool change event if the value changes Private Sub ManageBoolValueChanging( _ ByVal rowNum As Integer, _ ByVal colNum As Integer) Dim mousePos _ As Point = Me.DataGridTableStyle.DataGrid.PointToClient( _ Control.MousePosition) Dim dg As DataGrid = Me.DataGridTableStyle.DataGrid Dim isClickInCell As Boolean = _ Control.MouseButtons = MouseButtons.Left AndAlso _ dg.GetCellBounds(dg.CurrentCell).Contains(mousePos) Dim changing As Boolean = _ dg.Focused AndAlso isClickInCell _ OrElse GetKeyState(VK_SPACE) < 0 ' or spacebar If Not lockValue AndAlso _ beingEdited AndAlso _ changing AndAlso _ saveRow = rowNum Then saveValue = Not saveValue lockValue = False 'fire the event Dim e As New BoolValueChangedEventArgs( _ rowNum, colNum, saveValue) RaiseEvent BoolValueChanged(Me, e) End If If saveRow = rowNum Then lockValue = False End If End Sub 'ManageBoolValueChanging End Class
Using the ClickableBooleanColumn
To use the special column style, create an instance of it when setting up the columnstyle for the discontinuedCol. A handler for the new BoolValueChanged event will also be added.
' Discontinued. Dim discontinuedCol As New ClickableBooleanColumn() discontinuedCol.MappingName = "Discontinued" discontinuedCol.HeaderText = "" discontinuedCol.Width = 30 ' turn off tristate discontinuedCol.AllowNull = False AddHandler discontinuedCol.BoolValueChanged, _ AddressOf BoolCellClicked tableStyle.GridColumnStyles.Add(discontinuedCol)
The BoolValueChanged Event Handler
In the event handler, the row must be forced to be redrawn using the new value of the Boolean cell. Anytime the Boolean value changes, the event handler invalidates the rectangle associated with a row to reflect the proper format. To force a redraw of a row, use a RefreshRow helper method. In the event handler, the Boolean value is forced to be stored by ending the edit mode. Doing so allows the FormatGridRow method to obtain the proper value of the Boolean cell. Without this call, only the initial value of the cell is available through the indexed DataGrid.
Private Sub BoolCellClicked(ByVal sender As Object, _ ByVal e As BoolValueChangedEventArgs) Dim g As DataGrid = Me.DataGrid1 Dim discontinuedCol As New _ ClickableBooleanColumn = _ g.TableStyles(0).GridColumnStyles("Discontinued") g.EndEdit(discontinuedCol, e.Row, False) RefreshRow(e.Row) g.BeginEdit(discontinuedCol, e.Row) End Sub ' Forces a repaint of given row. Private Sub RefreshRow(ByVal row As Integer) Dim r As Rectangle = _ Me.dataGrid1.GetCellBounds(row, 0) r = New Rectangle(r.Right, r.Top, _ Me.dataGrid1.Width, r.Height) Me.dataGrid1.Invalidate(r) End Sub 'RefreshRow
There is one last problem to handle before clicking the check box to be certain that the cell behaves as expected with the row changing colors with each click. If a checkbox is clicked that is not checked and is not on the current row, then the click sets the row in the current row colors, instead of the discontinued colors. Furthermore, the problem appears strictly to be a refresh problem because dragging the grid on and off the display will cause the row to be redrawn using the expected discontinued format. This refresh problem can be handled by forcing the row to be refreshed during the existing dataGrid1_Click event handler. In that event, the code is executed to change the Boolean value, and also to refresh the row.
If afterCurrentCellChanged AndAlso _ hti.Row < bmb.Count AndAlso _ hti.Type = DataGrid.HitTestType.Cell AndAlso _ hti.Column = 0 Then Me.DataGrid1(hti.Row, 0) = _ Not CBool(Me.DataGrid1(hti.Row, 0)) RefreshRow(hti.Row) End If
Customization 6: Adding Row-Dependent ToolTips
The Windows Forms ToolTip class can be used to add a ToolTip for an entire DataGrid. To do so, drag the ToolTip component onto the Form and set the ToolTip property that is added to every control on the form. However, implementing a ToolTip in this manner does not allow the tip to be varied when moving from row to row (or cell to cell) in the DataGrid. The goal is to display a ToolTip that can be varied from row to row. Using the same strategy, ToolTips could be implemented that vary from cell to cell or column to column.
Start by adding two fields to the Form class, hitRow and ToolTip1. These fields are initialized in Form1_Load, and are dynamically changed in the dataGrid1_MouseMove event handler that was added. In the MouseMove, check that the cursor is over a new row, and if so, reset the ToolTip with different text. See the following code example:
Private hitRow As Integer Private toolTip1 As System.Windows.Forms.ToolTip ' In Form1_Load Me.hitRow = -1 Me.toolTip1 = New ToolTip() Me.toolTip1.InitialDelay = 300 AddHandler Me.DataGrid1.MouseMove, _ AddressOf dataGrid1_MouseMove Private Sub dataGrid1_MouseMove( _ ByVal sender As Object, _ ByVal e As MouseEventArgs) Dim g As DataGrid = Me.dataGrid1 Dim hti As DataGrid.HitTestInfo = _ g.HitTest(New Point(e.X, e.Y)) Dim bmb As BindingManagerBase = _ Me.BindingContext(g.DataSource, g.DataMember) If hti.Row < bmb.Count AndAlso _ hti.Type = DataGrid.HitTestType.Cell AndAlso _ hti.Row <> hitRow Then If Not (Me.toolTip1 Is Nothing) AndAlso _ Me.toolTip1.Active Then Me.toolTip1.Active = False 'turn it off End If Dim tipText As String = "" If CBool(Me.DataGrid1(hti.Row, 0)) Then tipText = Me.DataGrid1(hti.Row, 2).ToString() & _ " discontinued" If tipText <> "" Then 'new hit row hitRow = hti.Row Me.toolTip1.SetToolTip(Me.DataGrid1, tipText) ' make it active so it can show Me.toolTip1.Active = True Else hitRow = -1 End If Else hitRow = -1 End If End If End Sub 'dataGrid1_MouseMove
Figure 8 DataGrid Showing Row-Dependent ToolTips
The final DataGrid uses two derived DataGridColumnStyles to handle cell formatting and monitor Boolean value changes. The formatting is accomplished by overriding the derived classes' Paint method, and raising an event to allow a listener to furnish format information based on a row and column index. The derived class that manages Boolean values also overrides the Paint method, firing an event when the value changes at this point; in addition, it requires Edit and Commit overrides to fully manage this task.
Also used are form level events to control DataGrid behavior. The DataGrid.CurrentCellChanged event was used to force the current cell to a particular cell in the row, no matter which cell in the row was clicked. The DataGrid.Clicked event was used to make the CheckBox column responds to the first click, instead of requiring two clicks to change its value. Finally, the DataGrid.MouseMove event was used to make ToolTips dynamic by changing from row to row.
There are two samples accompanying this article in the attached download (see link at the top). The first one, CustomGrid, contains the VB .NET project that served as the source for all the code snippets in this discussion. The second, CustomGridA, contains two projects, one VB .NET and the other C#. The C# project is more involved than the one used in this discussion, but generally follows the same flow.