Data Grid View
Data Grid View
With the DataGridView control, you can display and edit tabular data
from many different kinds of data sources.
Binding data to the DataGridView control is straightforward and intuitive,
and in many cases it is as simple as setting the DataSource
[ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.datasource.aspx ] property.
When you bind to a data source that contains multiple lists or tables, set
the DataMember [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.datamember.aspx ]
property to a string that specifies the list or table to bind to.
The DataGridView control supports the standard Windows Forms data
binding model, so it will bind to instances of classes described in the
following list:
z Any class that implements the IList [ http://msdn2.microsoft.com/en-
us/library/system.collections.ilist.aspx ] interface, including one-
dimensional arrays.
z Any class that implements the IListSource
[ http://msdn2.microsoft.com/en-
us/library/system.componentmodel.ilistsource.aspx ] interface, such as
the DataTable [ http://msdn2.microsoft.com/en-
us/library/system.data.datatable.aspx ] and DataSet
[ http://msdn2.microsoft.com/en-us/library/system.data.dataset.aspx ]
classes.
z Any class that implements the IBindingList
[ http://msdn2.microsoft.com/en-
us/library/system.componentmodel.ibindinglist.aspx ] interface, such
as the BindingList [ http://msdn2.microsoft.com/en-
us/library/ms132679.aspx ] class.
z Any class that implements the IBindingListView
http://msdn2.microsoft.com/en-us/library/k39d6s23(d=printer).aspx 5/22/2007
DataGridView Control Overview (Windows Forms) Page 2 of 4
[ http://msdn2.microsoft.com/en-
us/library/system.componentmodel.ibindinglistview.aspx ] interface,
such as the BindingSource [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.bindingsource.aspx ] class.
The DataGridView control supports data binding to the public properties
of the objects returned by these interfaces or to the properties collection
returned by an ICustomTypeDescriptor [ http://msdn2.microsoft.com/en-
us/library/system.componentmodel.icustomtypedescriptor.aspx ] interface,
if implemented on the returned objects.
Typically, you will bind to a BindingSource component and bind the
BindingSource component to another data source or populate it with
business objects. The BindingSource component is the preferred data
source because it can bind to a wide variety of data sources and can
resolve many data binding issues automatically. For more information, see
BindingSource Component [ http://msdn2.microsoft.com/en-
us/library/h974h4y2.aspx ] .
The DataGridView control can also be used in unbound mode, with no
underlying data store. For a code example that uses an unbound
DataGridView control, see Walkthrough: Creating an Unbound Windows
Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/5s3ce6k8.aspx ] .
The DataGridView control is highly configurable and extensible, and it
provides many properties, methods, and events to customize its
appearance and behavior. When you want your Windows Forms application
to display tabular data, consider using the DataGridView control before
others (for example, DataGrid). If you are displaying a small grid of read-
only values, or if you are enabling a user to edit a table with millions of
records, the DataGridView control will provide you with a readily
programmable, memory-efficient solution.
In This Section
DataGridView Control Technology Summary (Windows Forms)
[ http://msdn2.microsoft.com/en-us/library/t4wtb0tc.aspx ]
Summarizes DataGridView control concepts and the use of related
classes.
DataGridView Control Architecture (Windows Forms)
[ http://msdn2.microsoft.com/en-us/library/dkdz8z4e.aspx ]
Describes the architecture of the DataGridView control, explaining
its type hierarchy and inheritance structure.
DataGridView Control Scenarios (Windows Forms)
[ http://msdn2.microsoft.com/en-us/library/s7za025w.aspx ]
Describes the most common scenarios in which DataGridView
controls are used.
http://msdn2.microsoft.com/en-us/library/k39d6s23(d=printer).aspx 5/22/2007
DataGridView Control Overview (Windows Forms) Page 3 of 4
http://msdn2.microsoft.com/en-us/library/k39d6s23(d=printer).aspx 5/22/2007
DataGridView Control Overview (Windows Forms) Page 4 of 4
Community Content
http://msdn2.microsoft.com/en-us/library/k39d6s23(d=printer).aspx 5/22/2007
DataGridView Control Technology Summary (Windows Forms) Page 1 of 4
Keywords
Namespaces
System.Windows.Forms [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.aspx ]
System.Data [ http://msdn2.microsoft.com/en-
us/library/system.data.aspx ]
Related Technologies
BindingSource
Background
http://msdn2.microsoft.com/en-us/library/t4wtb0tc(d=printer).aspx 5/22/2007
DataGridView Control Technology Summary (Windows Forms) Page 2 of 4
There are several ways for you to take advantage of the DataGridView
control's extensibility features. You can customize many aspects of the
control through events and properties, but some customizations require
you to create new classes derived from existing DataGridView classes.
The most typically used base classes are DataGridViewCell and
DataGridViewColumn. You can derive your own cell class from
DataGridViewCell or any of its child classes. Although you can add any
cell type to any column, you will typically also derive a companion column
class from DataGridViewColumn that hosts cells of your custom cell type
by default.
You can implement the IDataGridViewEditingCell interface in your
derived cell class to create a cell type that has editing functionality but
does not host a control in editing mode. To create a control that you can
host in a cell in editing mode, you can implement the
IDataGridViewEditingControl interface in a class derived from Control
[ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.control.aspx ] .
For more information, see How to: Customize Cells and Columns in the
Windows Forms DataGridView Control by Extending Their Behavior and
Appearance [ http://msdn2.microsoft.com/en-us/library/7fb61s43.aspx ]
and How to: Host Controls in Windows Forms DataGridView Cells
[ http://msdn2.microsoft.com/en-us/library/7tas5c80.aspx ] .
System.Windows.Forms
Technology Area Classes/interfaces/configuration elements
http://msdn2.microsoft.com/en-us/library/t4wtb0tc(d=printer).aspx 5/22/2007
DataGridView Control Technology Summary (Windows Forms) Page 3 of 4
DataGridViewCell [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcell.aspx ] and derived classes
DataGridViewRow [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewrow.aspx ] and derived classes
DataGridViewColumn [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcolumn.aspx ] and derived classes
DataGridViewCellStyle [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcellstyle.aspx ]
IDataGridViewEditingCell [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.idatagridvieweditingcell.aspx ]
IDataGridViewEditingControl [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.idatagridvieweditingcontrol.aspx ]
What's New
See Also
Reference
DataGridView Control Overview (Windows Forms)
[ http://msdn2.microsoft.com/en-us/library/k39d6s23.aspx ]
Concepts
DataGridView Control Architecture (Windows Forms)
[ http://msdn2.microsoft.com/en-us/library/dkdz8z4e.aspx ]
Securing Connection Strings [ http://msdn2.microsoft.com/en-
us/library/89211k9b.aspx ]
http://msdn2.microsoft.com/en-us/library/t4wtb0tc(d=printer).aspx 5/22/2007
DataGridView Control Technology Summary (Windows Forms) Page 4 of 4
Community Content
http://msdn2.microsoft.com/en-us/library/t4wtb0tc(d=printer).aspx 5/22/2007
DataGridView Control Architecture (Windows Forms) Page 1 of 7
Architecture Elements
http://msdn2.microsoft.com/en-us/library/dkdz8z4e(d=printer).aspx 5/22/2007
DataGridView Control Architecture (Windows Forms) Page 2 of 7
us/library/system.windows.forms.datagridviewelementstates.aspx ]
z ReadOnly [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewelementstates.aspx ]
z Resizable [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewelementstates.aspx ]
z ResizableSet [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewelementstates.aspx ]
z Selected [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewelementstates.aspx ]
z Visible [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewelementstates.aspx ]
The values of this enumeration can be combined with the bitwise logical
operators, so the State property can express more than one state at once.
For example, a DataGridViewElement can be simultaneously Frozen,
Selected, and Visible.
Cells and Bands
The DataGridView control comprises two fundamental kinds of objects:
cells and bands. All cells derive from the DataGridViewCell
[ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcell.aspx ] base class. The
two kinds of bands, DataGridViewColumn
[ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcolumn.aspx ] and
DataGridViewRow [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewrow.aspx ] , both derive
from the DataGridViewBand [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewband.aspx ] base class.
The DataGridView control interoperates with several classes, but the
most commonly encountered are DataGridViewCell,
DataGridViewColumn, and DataGridViewRow.
DataGridViewCell
The cell is the fundamental unit of interaction for the DataGridView.
Display is centered on cells, and data entry is often performed through
cells. You can access cells by using the Cells
[ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewrow.cells.aspx ] collection of
the DataGridViewRow class, and you can access the selected cells by
using the SelectedCells [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.selectedcells.aspx ]
collection of the DataGridView control. The following object model
illustrates this usage and shows the DataGridViewCell inheritance
hierarchy.
DataGridViewCell object model
http://msdn2.microsoft.com/en-us/library/dkdz8z4e(d=printer).aspx 5/22/2007
DataGridView Control Architecture (Windows Forms) Page 3 of 7
The DataGridViewCell type is an abstract base class, from which all cell
types derive. DataGridViewCell and its derived types are not Windows
Forms controls, but some host Windows Forms controls. Any editing
functionality supported by a cell is typically handled by a hosted control.
DataGridViewCell objects do not control their own appearance and
painting features in the same way as Windows Forms controls. Instead, the
DataGridView is responsible for the appearance of its DataGridViewCell
objects. You can significantly affect the appearance and behavior of cells by
interacting with the DataGridView control's properties and events. When
you have special requirements for customizations that are beyond the
capabilities of the DataGridView control, you can implement your own
class that derives from DataGridViewCell or one of its child classes.
The following list shows the classes derived from DataGridViewCell:
z DataGridViewTextBoxCell [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewtextboxcell.aspx ]
z DataGridViewButtonCell [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewbuttoncell.aspx ]
z DataGridViewLinkCell [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewlinkcell.aspx ]
z DataGridViewCheckBoxCell [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcheckboxcell.aspx ]
http://msdn2.microsoft.com/en-us/library/dkdz8z4e(d=printer).aspx 5/22/2007
DataGridView Control Architecture (Windows Forms) Page 4 of 7
z DataGridViewComboBoxCell [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcomboboxcell.aspx ]
z DataGridViewImageCell [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewimagecell.aspx ]
z DataGridViewHeaderCell [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewheadercell.aspx ]
z DataGridViewRowHeaderCell [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewrowheadercell.aspx ]
z DataGridViewColumnHeaderCell [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcolumnheadercell.aspx ]
z DataGridViewTopLeftHeaderCell [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewtopleftheadercell.aspx ]
z Your custom cell types
DataGridViewColumn
The schema of the DataGridView control's attached data store is
expressed in the DataGridView control's columns. You can access the
DataGridView control's columns by using the Columns
[ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.columns.aspx ] collection.
You can access the selected columns by using the SelectedColumns
[ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.selectedcolumns.aspx ]
collection. The following object model illustrates this usage and shows the
DataGridViewColumn inheritance hierarchy.
DataGridViewColumn object model
http://msdn2.microsoft.com/en-us/library/dkdz8z4e(d=printer).aspx 5/22/2007
DataGridView Control Architecture (Windows Forms) Page 5 of 7
Some of the key cell types have corresponding column types. These are
derived from the DataGridViewColumn base class.
The following list shows the classes derived from DataGridViewColumn:
z DataGridViewButtonColumn [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewbuttoncolumn.aspx ]
z DataGridViewCheckBoxColumn [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcheckboxcolumn.aspx ]
z DataGridViewComboBoxColumn [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcomboboxcolumn.aspx ]
z DataGridViewImageColumn [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewimagecolumn.aspx ]
z DataGridViewTextBoxColumn [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewtextboxcolumn.aspx ]
z DataGridViewLinkColumn [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewlinkcolumn.aspx ]
z Your custom column types
DataGridView Editing Controls
Cells that support advanced editing functionality typically use a hosted
control that is derived from a Windows Forms control. These controls also
implement the IDataGridViewEditingControl
[ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.idatagridvieweditingcontrol.aspx ]
interface. The following object model illustrates the usage of these
controls.
DataGridView editing control object model
The following editing controls are provided with the DataGridView control:
z DataGridViewComboBoxEditingControl
[ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcomboboxeditingcontrol.aspx ]
z DataGridViewTextBoxEditingControl [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewtextboxeditingcontrol.aspx ]
http://msdn2.microsoft.com/en-us/library/dkdz8z4e(d=printer).aspx 5/22/2007
DataGridView Control Architecture (Windows Forms) Page 6 of 7
For information about creating your own editing controls, see How to: Host
Controls in Windows Forms DataGridView Cells
[ http://msdn2.microsoft.com/en-us/library/7tas5c80.aspx ] .
The following table illustrates the relationship among cell types, column
types, and editing controls.
Cell type Hosted control Column type
DataGridViewRow
The DataGridViewRow class displays a record's data fields from the data
store to which the DataGridView control is attached. You can access the
DataGridView control's rows by using the Rows
[ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.rows.aspx ] collection. You
can access the selected rows by using the SelectedRows
[ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.selectedrows.aspx ]
collection. The following object model illustrates this usage and shows the
DataGridViewRow inheritance hierarchy.
DataGridViewRow object model
You can derive your own types from the DataGridViewRow class,
although this will typically not be necessary. The DataGridView control
has several row-related events and properties for customizing the behavior
http://msdn2.microsoft.com/en-us/library/dkdz8z4e(d=printer).aspx 5/22/2007
DataGridView Control Architecture (Windows Forms) Page 7 of 7
See Also
Reference
DataGridView Control Overview (Windows Forms)
[ http://msdn2.microsoft.com/en-us/library/k39d6s23.aspx ]
Concepts
Using the Row for New Records in the Windows Forms DataGridView
Control [ http://msdn2.microsoft.com/en-us/library/ka3w9f4d.aspx ]
Other Resources
Customizing the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/ms171618.aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/dkdz8z4e(d=printer).aspx 5/22/2007
DataGridView Control Scenarios (Windows Forms) Page 1 of 4
You do not have to store your data in an external data source to display it
in the DataGridView control. If you are working with a small amount of
data, you can populate the control yourself and manipulate the data
through the control. This is called unbound mode. For more information,
see How to: Create an Unbound Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/zf3zx9fy.aspx ] .
Scenario Key Points
z In unbound mode, you populate the control manually.
You can use the DataGridView control as a user interface (UI) through
which users can access data kept in a data source such as a database table
or a collection of business objects. For more information, see How to: Bind
Data to the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/fbk67b6z.aspx ] .
Scenario Key Points
z Bound mode lets you connect to a data source, automatically generate
http://msdn2.microsoft.com/en-us/library/s7za025w(d=printer).aspx 5/22/2007
DataGridView Control Scenarios (Windows Forms) Page 2 of 4
If you have special needs that the standard data binding model does not
address, you can manage the interaction between the control and your
data by implementing virtual mode. Implementing virtual mode means
implementing one or more event handlers that let the control request
information about cells as the information is needed.
For example, if you work with large amounts of data, you may want to
implement virtual mode to ensure optimal efficiency. Virtual mode is also
useful for maintaining the values of unbound columns that you display
along with columns retrieved from another data source.
For more information about virtual mode, see Walkthrough: Implementing
Virtual Mode in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/15a31akc.aspx ] .
Scenario Key Points
z Virtual mode is suited for displaying very large amounts of data when
When you display data that is regularly updated, you can automatically
resize rows and columns to ensure that all content is visible. The
DataGridView control provides several options that let you enable or
disable manual resizing, resize programmatically at specific times, or resize
automatically whenever content changes. For more information, see Sizing
Options in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/74b2wakt.aspx ] .
Scenario Key Points
z Manual resizing enables users to adjust cell heights and widths.
http://msdn2.microsoft.com/en-us/library/s7za025w(d=printer).aspx 5/22/2007
DataGridView Control Scenarios (Windows Forms) Page 3 of 4
The DataGridView control provides many ways for you to alter its basic
appearance and behavior. For more information, see Cell Styles in the
Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/1yef90x0.aspx ] .
Scenario Key Points
z DataGridViewCellStyle [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcellstyle.aspx ] objects
let you provide color, font, formatting, and positioning information at
multiple levels and for individual elements of the control.
z Cell styles can be layered and shared by multiple elements, letting you
reuse code.
The DataGridView control provides many ways for you to customize its
appearance and behavior.
Scenario Key Points
z You can provide your own cell painting code. For more information, see
See Also
http://msdn2.microsoft.com/en-us/library/s7za025w(d=printer).aspx 5/22/2007
DataGridView Control Scenarios (Windows Forms) Page 4 of 4
Reference
DataGridView Control Overview (Windows Forms)
[ http://msdn2.microsoft.com/en-us/library/k39d6s23.aspx ]
DataGridView [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/s7za025w(d=printer).aspx 5/22/2007
DataGridView Control Code Directory (Windows Forms) Page 1 of 5
A link always jumps to the top of the topic in which the code example is found.
[ http://msdn2.microsoft.com/en-us/library/fbk67b6z(VS.80).aspx ]
z How to: Autogenerate Columns in a Data-Bound Windows Forms
DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/28bfhf10(VS.80).aspx ]
z How to: Remove Autogenerated Columns from a Windows Forms
DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/hbtwc35f(VS.80).aspx ]
z How to: Bind Objects to Windows Forms DataGridView Controls
[ http://msdn2.microsoft.com/en-us/library/y0wfd4yz(VS.80).aspx ]
z How to: Access Objects Bound to Windows Forms DataGridView Rows
[ http://msdn2.microsoft.com/en-us/library/4wszzzc7(VS.80).aspx ]
z How to: Create a Master/Detail Form Using Two Windows Forms
http://msdn2.microsoft.com/en-us/library/8adxw4f4(vs.80,d=printer).aspx 5/22/2007
DataGridView Control Code Directory (Windows Forms) Page 2 of 5
[ http://msdn2.microsoft.com/en-us/library/f9x2790s(VS.80).aspx ]
z How to: Customize Data Formatting in the Windows Forms
DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/z1cc356h(VS.80).aspx ]
Data Validation Examples
z How to: Validate Data in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/7ehy30d4(VS.80).aspx ]
z Walkthrough: Validating Data in the Windows Forms DataGridView
Control [ http://msdn2.microsoft.com/en-us/library/ykdxa0bc
(VS.80).aspx ]
z How to: Handle Errors That Occur During Data Entry in the Windows
Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/xktax5sd(VS.80).aspx ]
z Walkthrough: Handling Errors that Occur During Data Entry in the
Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/t4a23xx4(VS.80).aspx ]
Appearance Customization Examples
z How to: Change the Border and Gridline Styles in the Windows Forms
Control [ http://msdn2.microsoft.com/en-us/library/yztkd864
(VS.80).aspx ]
http://msdn2.microsoft.com/en-us/library/8adxw4f4(vs.80,d=printer).aspx 5/22/2007
DataGridView Control Code Directory (Windows Forms) Page 3 of 5
z How to: Specify Default Values for New Rows in the Windows Forms
DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/b22t666e(VS.80).aspx ]
z How to: Prevent Row Addition and Deletion in the Windows Forms
DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/61bk13ye(VS.80).aspx ]
z How to: Perform a Custom Action Based on Changes in a Cell of a
Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/ewk0cc1s(VS.80).aspx ]
z How to: Enable Users to Copy Multiple Cells to the Clipboard from the
Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/dec5efh1(VS.80).aspx ]
z How to: Add ToolTips to Individual Cells in a Windows Forms
DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/2249cf0a(VS.80).aspx ]
z How to: Display Images in Cells of the Windows Forms DataGridView
Control [ http://msdn2.microsoft.com/en-us/library/2ab8kd75
(VS.80).aspx ]
z How to: Customize Sorting in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/ms171608(VS.80).aspx ]
Column Manipulation Examples
z How to: Freeze Columns in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/28e9w2e1(VS.80).aspx ]
z How to: Enable Column Reordering in the Windows Forms
DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/510kh8zh(VS.80).aspx ]
z How to: Change the Order of Columns in the Windows Forms
DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/wkfe535h(VS.80).aspx ]
z How to: Hide Columns in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/0c24a0d7(VS.80).aspx ]
z How to: Hide Column Headers in the Windows Forms DataGridView
Control [ http://msdn2.microsoft.com/en-us/library/2x16tybz
(VS.80).aspx ]
z How to: Make Columns Read-Only in the Windows Forms DataGridView
Control [ http://msdn2.microsoft.com/en-us/library/cze614bb
(VS.80).aspx ]
z How to: Set the Sort Modes for Columns in the Windows Forms
DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/8b9k0ktw(VS.80).aspx ]
z How to: Work with Image Columns in the Windows Forms DataGridView
Control [ http://msdn2.microsoft.com/en-us/library/x0tz73t0
(VS.80).aspx ]
http://msdn2.microsoft.com/en-us/library/8adxw4f4(vs.80,d=printer).aspx 5/22/2007
DataGridView Control Code Directory (Windows Forms) Page 4 of 5
[ http://msdn2.microsoft.com/en-us/library/ms171605(VS.80).aspx ]
z How to: Set the Sizing Modes of the Windows Forms DataGridView
Control [ http://msdn2.microsoft.com/en-us/library/fd004dhd
(VS.80).aspx ]
z How to: Programmatically Resize Cells to Fit Content in the Windows
Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/ff173xd4(VS.80).aspx ]
z How to: Automatically Resize Cells When Content Changes in the
Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/f71f07b5(VS.80).aspx ]
Selection Examples
z How to: Set the Selection Mode of the Windows Forms DataGridView
Control [ http://msdn2.microsoft.com/en-us/library/wfc9h72k
(VS.80).aspx ]
z How to: Get the Selected Cells, Rows, and Columns in the Windows
Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/x8x9zk5a(VS.80).aspx ]
z How to: Get and Set the Current Cell in the Windows Forms
DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/yc4fsbf5(VS.80).aspx ]
Advanced Customization Examples
z How to: Customize the Appearance of Cells in the Windows Forms
Control [ http://msdn2.microsoft.com/en-us/library/2b177d6d
http://msdn2.microsoft.com/en-us/library/8adxw4f4(vs.80,d=printer).aspx 5/22/2007
DataGridView Control Code Directory (Windows Forms) Page 5 of 5
(VS.80).aspx ]
z Walkthrough: Implementing Virtual Mode in the Windows Forms
DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/15a31akc(VS.80).aspx ]
z Implementing Virtual Mode with Just-In-Time Data Loading in the
Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/ms171624(VS.80).aspx ]
See Also
Reference
DataGridView Control Overview (Windows Forms)
[ http://msdn2.microsoft.com/en-us/library/k39d6s23(VS.80).aspx ]
DataGridView [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/8adxw4f4(vs.80,d=printer).aspx 5/22/2007
Default Functionality in the Windows Forms DataGridView Control Page 1 of 2
Default Functionality
http://msdn2.microsoft.com/en-us/library/ak81b67y(vs.80,d=printer).aspx 5/22/2007
Default Functionality in the Windows Forms DataGridView Control Page 2 of 2
See Also
Reference
DataGridView [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview(VS.80).aspx ]
Other Resources
DataGridView Control (Windows Forms) [ http://msdn2.microsoft.com/en-
us/library/e0ywh3cz(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/ak81b67y(vs.80,d=printer).aspx 5/22/2007
Column Types in the Windows Forms DataGridView Control Page 1 of 6
http://msdn2.microsoft.com/en-us/library/bxt3k60s(vs.80,d=printer).aspx 5/22/2007
Column Types in the Windows Forms DataGridView Control Page 2 of 6
Your custom column type You can create your own column class by i
the DataGridViewColumn
[ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridv
(VS.80).aspx ] class or any of its derived c
provide custom appearance, behavior, or h
controls. For more information, see How to
Customize Cells and Columns in the Windo
DataGridView Control by Extending Their B
and Appearance [ http://msdn2.microsoft.
us/library/7fb61s43(VS.80).aspx ]
These column types are described in more detail in the following sections.
DataGridViewTextBoxColumn
DataGridViewCheckBoxColumn
http://msdn2.microsoft.com/en-us/library/bxt3k60s(vs.80,d=printer).aspx 5/22/2007
Column Types in the Windows Forms DataGridView Control Page 3 of 6
DataGridViewImageColumn
http://msdn2.microsoft.com/en-us/library/bxt3k60s(vs.80,d=printer).aspx 5/22/2007
Column Types in the Windows Forms DataGridView Control Page 4 of 6
DataGridViewButtonColumn
DataGridViewComboBoxColumn
http://msdn2.microsoft.com/en-us/library/bxt3k60s(vs.80,d=printer).aspx 5/22/2007
Column Types in the Windows Forms DataGridView Control Page 5 of 6
[ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcolumn.datapropertyname
(VS.80).aspx ] property of the
System.Windows.Forms.DataGridViewComboBoxColumn.
Combo box columns are not generated automatically when data-binding a
DataGridView control. To use combo box columns, you must create them
manually and add them to the collection returned by the Columns
property.
DataGridViewLinkColumn
See Also
Tasks
How to: Display Images in Cells of the Windows Forms DataGridView
Control [ http://msdn2.microsoft.com/en-us/library/2ab8kd75
(VS.80).aspx ]
How to: Work with Image Columns in the Windows Forms DataGridView
Control [ http://msdn2.microsoft.com/en-us/library/x0tz73t0
(VS.80).aspx ]
Reference
DataGridView [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview(VS.80).aspx ]
DataGridViewColumn [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcolumn(VS.80).aspx ]
http://msdn2.microsoft.com/en-us/library/bxt3k60s(vs.80,d=printer).aspx 5/22/2007
Column Types in the Windows Forms DataGridView Control Page 6 of 6
DataGridViewButtonColumn [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewbuttoncolumn(VS.80).aspx ]
DataGridViewCheckBoxColumn [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcheckboxcolumn
(VS.80).aspx ]
DataGridViewComboBoxColumn [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcomboboxcolumn
(VS.80).aspx ]
DataGridViewImageColumn [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewimagecolumn(VS.80).aspx ]
DataGridViewTextBoxColumn [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewtextboxcolumn
(VS.80).aspx ]
DataGridViewLinkColumn [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewlinkcolumn(VS.80).aspx ]
Other Resources
DataGridView Control (Windows Forms) [ http://msdn2.microsoft.com/en-
us/library/e0ywh3cz(VS.80).aspx ]
Customizing the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/ms171618(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/bxt3k60s(vs.80,d=printer).aspx 5/22/2007
Basic Column, Row, and Cell Features in the Windows Forms DataGridView Control Page 1 of 2
In This Section
http://msdn2.microsoft.com/en-us/library/ms171596(vs.80,d=printer).aspx 5/22/2007
Basic Column, Row, and Cell Features in the Windows Forms DataGridView Control Page 2 of 2
control.
How to: Display Images in Cells of the Windows Forms DataGridView
Control [ http://msdn2.microsoft.com/en-us/library/2ab8kd75
(VS.80).aspx ]
Describes how to create an image column that displays an icon in
every cell.
Reference
DataGridView [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview(VS.80).aspx ]
Provides reference documentation for the control.
Related Sections
See Also
Concepts
Column Types in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/bxt3k60s(VS.80).aspx ]
Other Resources
DataGridView Control (Windows Forms) [ http://msdn2.microsoft.com/en-
us/library/e0ywh3cz(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/ms171596(vs.80,d=printer).aspx 5/22/2007
How to: Hide Columns in the Windows Forms DataGridView Control Page 1 of 2
C# Copy Code
this.dataGridView1.Columns["CustomerID"].Visible = false;
http://msdn2.microsoft.com/en-us/library/0c24a0d7(vs.80,d=printer).aspx 5/22/2007
How to: Hide Columns in the Windows Forms DataGridView Control Page 2 of 2
See Also
Tasks
How to: Remove Autogenerated Columns from a Windows Forms
DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/hbtwc35f(VS.80).aspx ]
How to: Change the Order of Columns in the Windows Forms DataGridView
Control [ http://msdn2.microsoft.com/en-us/library/wkfe535h
(VS.80).aspx ]
Reference
DataGridView [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview(VS.80).aspx ]
System.Windows.Forms.DataGridViewColumn.Visible
[ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcolumn.visible(VS.80).aspx ]
Other Resources
Basic Column, Row, and Cell Features in the Windows Forms DataGridView
Control [ http://msdn2.microsoft.com/en-us/library/ms171596
(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/0c24a0d7(vs.80,d=printer).aspx 5/22/2007
How to: Hide Column Headers in the Windows Forms DataGridView Control Page 1 of 2
z Set the
System.Windows.Forms.DataGridView.ColumnHeadersVisible
property to false.
C# Copy Code
dataGridView1.ColumnHeadersVisible = false;
See Also
Reference
DataGridView [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview(VS.80).aspx ]
System.Windows.Forms.DataGridView.ColumnHeadersVisible
http://msdn2.microsoft.com/en-us/library/2x16tybz(vs.80,d=printer).aspx 5/22/2007
How to: Hide Column Headers in the Windows Forms DataGridView Control Page 2 of 2
[ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.columnheadersvisible
(VS.80).aspx ]
Other Resources
Basic Column, Row, and Cell Features in the Windows Forms DataGridView
Control [ http://msdn2.microsoft.com/en-us/library/ms171596
(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/2x16tybz(vs.80,d=printer).aspx 5/22/2007
How to: Enable Column Reordering in the Windows Forms DataGridView Control Page 1 of 2
z Set the
System.Windows.Forms.DataGridView.AllowUserToOrderColumns
property to true.
C# Copy Code
dataGridView1.AllowUserToOrderColumns = true;
http://msdn2.microsoft.com/en-us/library/510kh8zh(vs.80,d=printer).aspx 5/22/2007
How to: Enable Column Reordering in the Windows Forms DataGridView Control Page 2 of 2
[ http://msdn2.microsoft.com/en-us/library/system.windows.forms
(VS.80).aspx ] assemblies.
See Also
Tasks
How to: Freeze Columns in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/28e9w2e1(VS.80).aspx ]
Reference
DataGridView [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview(VS.80).aspx ]
System.Windows.Forms.DataGridView.AllowUserToOrderColumns
[ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.allowusertoordercolumns
(VS.80).aspx ]
Other Resources
Basic Column, Row, and Cell Features in the Windows Forms DataGridView
Control [ http://msdn2.microsoft.com/en-us/library/ms171596
(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/510kh8zh(vs.80,d=printer).aspx 5/22/2007
How to: Freeze Columns in the Windows Forms DataGridView Control Page 1 of 2
If column reordering is enabled, the frozen columns are treated as a group distinct from the unfrozen
columns. Users can reposition columns in either group, but they cannot move a column from one
group to the other.
C# Copy Code
http://msdn2.microsoft.com/en-us/library/28e9w2e1(vs.80,d=printer).aspx 5/22/2007
How to: Freeze Columns in the Windows Forms DataGridView Control Page 2 of 2
this.dataGridView1.Columns["AddToCartButton"].Frozen = true;
See Also
Tasks
How to: Enable Column Reordering in the Windows Forms DataGridView
Control [ http://msdn2.microsoft.com/en-us/library/510kh8zh
(VS.80).aspx ]
Reference
System.Windows.Forms.DataGridViewColumn.Frozen
[ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcolumn.frozen(VS.80).aspx ]
DataGridView [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview(VS.80).aspx ]
Other Resources
Basic Column, Row, and Cell Features in the Windows Forms DataGridView
Control [ http://msdn2.microsoft.com/en-us/library/ms171596
(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/28e9w2e1(vs.80,d=printer).aspx 5/22/2007
How to: Make Columns Read-Only in the Windows Forms DataGridView Control Page 1 of 2
C# Copy Code
dataGridView1.Columns["CompanyName"].ReadOnly = true;
http://msdn2.microsoft.com/en-us/library/cze614bb(vs.80,d=printer).aspx 5/22/2007
How to: Make Columns Read-Only in the Windows Forms DataGridView Control Page 2 of 2
[ http://msdn2.microsoft.com/en-us/library/system.windows.forms
(VS.80).aspx ] assemblies.
See Also
Tasks
How to: Prevent Row Addition and Deletion in the Windows Forms
DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/61bk13ye(VS.80).aspx ]
Reference
DataGridView [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview(VS.80).aspx ]
System.Windows.Forms.DataGridView.Columns
[ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.columns(VS.80).aspx ]
System.Windows.Forms.DataGridViewColumn.ReadOnly
[ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcolumn.readonly
(VS.80).aspx ]
Other Resources
Basic Column, Row, and Cell Features in the Windows Forms DataGridView
Control [ http://msdn2.microsoft.com/en-us/library/ms171596
(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/cze614bb(vs.80,d=printer).aspx 5/22/2007
How to: Prevent Row Addition and Deletion in the Windows Forms DataGridView Control Page 1 of 2
Example
With dataGridView1
.AllowUserToAddRows = False
.AllowUserToDeleteRows = False
.ReadOnly = True
End With
End Sub
C# Copy Code
private void MakeReadOnly()
http://msdn2.microsoft.com/en-us/library/61bk13ye(vs.80,d=printer).aspx 5/22/2007
How to: Prevent Row Addition and Deletion in the Windows Forms DataGridView Control Page 2 of 2
{
dataGridView1.AllowUserToAddRows = false;
dataGridView1.AllowUserToDeleteRows = false;
dataGridView1.ReadOnly = true;
}
See Also
Reference
DataGridView [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview(VS.80).aspx ]
System.Windows.Forms.DataGridView.AllowUserToAddRows
[ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.allowusertoaddrows
(VS.80).aspx ]
System.Windows.Forms.DataGridView.ReadOnly
[ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.readonly(VS.80).aspx ]
System.Windows.Forms.DataGridView.AllowUserToAddRows
[ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.allowusertoaddrows
(VS.80).aspx ]
System.Windows.Forms.DataGridView.AllowUserToDeleteRows
[ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.allowusertodeleterows
(VS.80).aspx ]
Other Resources
Basic Column, Row, and Cell Features in the Windows Forms DataGridView
Control [ http://msdn2.microsoft.com/en-us/library/ms171596
(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/61bk13ye(vs.80,d=printer).aspx 5/22/2007
How to: Get and Set the Current Cell in the Windows Forms DataGridView Control Page 1 of 3
You cannot set the current cell in a row or column that has its Visible
[ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridviewband.visible
(VS.80).aspx ] property set to false.
End Sub
C# Copy Code
private void getCurrentCellButton_Click(object sender, System.Ev
{
string msg = String.Format("Row: {0}, Column: {1}",
dataGridView1.CurrentCell.RowIndex,
dataGridView1.CurrentCell.ColumnIndex);
MessageBox.Show(msg, "Current Cell");
http://msdn2.microsoft.com/en-us/library/yc4fsbf5(vs.80,d=printer).aspx 5/22/2007
How to: Get and Set the Current Cell in the Windows Forms DataGridView Control Page 2 of 3
End Sub
C# Copy Code
private void setCurrentCellButton_Click(object sender, System.Ev
{
// Set the current cell to the cell in column 1, Row 0.
this.dataGridView1.CurrentCell = this.dataGridView1[1,0];
}
See Also
Reference
DataGridView [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview(VS.80).aspx ]
System.Windows.Forms.DataGridView.CurrentCell
http://msdn2.microsoft.com/en-us/library/yc4fsbf5(vs.80,d=printer).aspx 5/22/2007
How to: Get and Set the Current Cell in the Windows Forms DataGridView Control Page 3 of 3
[ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.currentcell(VS.80).aspx ]
Concepts
Selection Modes in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/8x6w9028(VS.80).aspx ]
Other Resources
Basic Column, Row, and Cell Features in the Windows Forms DataGridView
Control [ http://msdn2.microsoft.com/en-us/library/ms171596
(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/yc4fsbf5(vs.80,d=printer).aspx 5/22/2007
How to: Display Images in Cells of the Windows Forms DataGridView Control Page 1 of 2
Example
With iconColumn
.Image = treeIcon.ToBitmap()
.Name = "Tree"
.HeaderText = "Nice tree"
End With
dataGridView1.Columns.Insert(2, iconColumn)
End Sub
C# Copy Code
http://msdn2.microsoft.com/en-us/library/2ab8kd75(vs.80,d=printer).aspx 5/22/2007
How to: Display Images in Cells of the Windows Forms DataGridView Control Page 2 of 2
See Also
Tasks
How to: Customize Data Formatting in the Windows Forms DataGridView
Control [ http://msdn2.microsoft.com/en-us/library/z1cc356h
(VS.80).aspx ]
Reference
DataGridView [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview(VS.80).aspx ]
Other Resources
Basic Column, Row, and Cell Features in the Windows Forms DataGridView
Control [ http://msdn2.microsoft.com/en-us/library/ms171596
(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/2ab8kd75(vs.80,d=printer).aspx 5/22/2007
Basic Formatting and Styling in the Windows Forms DataGridView Control Page 1 of 3
In This Section
How to: Change the Border and Gridline Styles in the Windows Forms
DataGridView Control [ http://msdn2.microsoft.com/en-us/library/ehz9ksfa
(VS.80).aspx ]
Describes how to set DataGridView properties that define the
appearance of the control border and the boundary lines between
cells.
Cell Styles in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/1yef90x0(VS.80).aspx ]
Describes the DataGridViewCellStyle class and how properties of
that type interact to define how cells are displayed in the control.
How to: Set Default Cell Styles for the Windows Forms DataGridView
Control [ http://msdn2.microsoft.com/en-us/library/k4sab6f9
(VS.80).aspx ]
Describes how to use DataGridViewCellStyle properties to define
the default appearance of cells in specific rows and columns and in the
entire control.
How to: Format Data in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/f9x2790s(VS.80).aspx ]
Describes how to format cell display values using
DataGridViewCellStyle properties.
How to: Set Font and Color Styles in the Windows Forms DataGridView
Control [ http://msdn2.microsoft.com/en-us/library/z2akwyy7
(VS.80).aspx ]
Describes how to use the DefaultCellStyle property to set basic
display characteristics for all cells in the control.
http://msdn2.microsoft.com/en-us/library/ms171598(vs.80,d=printer).aspx 5/22/2007
Basic Formatting and Styling in the Windows Forms DataGridView Control Page 2 of 3
How to: Set Alternating Row Styles for the Windows Forms DataGridView
Control [ http://msdn2.microsoft.com/en-us/library/txth0a6h
(VS.80).aspx ]
Describes how to create a ledger-like effect in the control using
alternating rows that are displayed differently.
How to: Use the Row Template to Customize Rows in the Windows Forms
DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/d2bkk9d1(VS.80).aspx ]
Describes how to use the RowTemplate property to set row
properties that will be used for all rows in the control.
Reference
DataGridView [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview(VS.80).aspx ]
Provides reference documentation for the DataGridView control.
DataGridViewCellStyle [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcellstyle(VS.80).aspx ]
Provides reference documentation for the DataGridViewCellStyle
class.
CellFormatting [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.cellformatting
(VS.80).aspx ]
Provides reference documentation for the CellFormatting event.
RowTemplate [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.rowtemplate(VS.80).aspx ]
Provides reference documentation for the RowTemplate property.
Related Sections
See Also
Other Resources
DataGridView Control (Windows Forms) [ http://msdn2.microsoft.com/en-
http://msdn2.microsoft.com/en-us/library/ms171598(vs.80,d=printer).aspx 5/22/2007
Basic Formatting and Styling in the Windows Forms DataGridView Control Page 3 of 3
us/library/e0ywh3cz(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/ms171598(vs.80,d=printer).aspx 5/22/2007
How to: Change the Border and Gridline Styles in the Windows Forms DataGridView Co... Page 1 of 4
C# Copy Code
this.dataGridView1.GridColor = Color.BlueViolet;
http://msdn2.microsoft.com/en-us/library/ehz9ksfa(vs.80,d=printer).aspx 5/22/2007
How to: Change the Border and Gridline Styles in the Windows Forms DataGridView Co... Page 2 of 4
us/library/system.windows.forms.datagridview.borderstyle
(VS.80).aspx ] property to one of the BorderStyle
[ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.borderstyle(VS.80).aspx ]
enumeration values.
C# Copy Code
this.dataGridView1.BorderStyle = BorderStyle.Fixed3D;
C# Copy Code
this.dataGridView1.CellBorderStyle =
DataGridViewCellBorderStyle.None;
this.dataGridView1.RowHeadersBorderStyle =
DataGridViewHeaderBorderStyle.Single;
this.dataGridView1.ColumnHeadersBorderStyle =
DataGridViewHeaderBorderStyle.Single;
Example
http://msdn2.microsoft.com/en-us/library/ehz9ksfa(vs.80,d=printer).aspx 5/22/2007
How to: Change the Border and Gridline Styles in the Windows Forms DataGridView Co... Page 3 of 4
With Me.dataGridView1
.GridColor = Color.BlueViolet
.BorderStyle = BorderStyle.Fixed3D
.CellBorderStyle = DataGridViewCellBorderStyle.None
.RowHeadersBorderStyle = _
DataGridViewHeaderBorderStyle.Single
.ColumnHeadersBorderStyle = _
DataGridViewHeaderBorderStyle.Single
End With
End Sub
C# Copy Code
private void SetBorderAndGridlineStyles()
{
this.dataGridView1.GridColor = Color.BlueViolet;
this.dataGridView1.BorderStyle = BorderStyle.Fixed3D;
this.dataGridView1.CellBorderStyle =
DataGridViewCellBorderStyle.None;
this.dataGridView1.RowHeadersBorderStyle =
DataGridViewHeaderBorderStyle.Single;
this.dataGridView1.ColumnHeadersBorderStyle =
DataGridViewHeaderBorderStyle.Single;
}
See Also
Reference
BorderStyle [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.borderstyle(VS.80).aspx ]
System.Windows.Forms.DataGridView.BorderStyle
[ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.borderstyle(VS.80).aspx ]
System.Windows.Forms.DataGridView.CellBorderStyle
[ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.cellborderstyle
http://msdn2.microsoft.com/en-us/library/ehz9ksfa(vs.80,d=printer).aspx 5/22/2007
How to: Change the Border and Gridline Styles in the Windows Forms DataGridView Co... Page 4 of 4
(VS.80).aspx ]
System.Windows.Forms.DataGridView.ColumnHeadersBorderStyle
[ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.columnheadersborderstyle
(VS.80).aspx ]
System.Windows.Forms.DataGridView.GridColor
[ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.gridcolor(VS.80).aspx ]
System.Windows.Forms.DataGridView.RowHeadersBorderStyle
[ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.rowheadersborderstyle
(VS.80).aspx ]
DataGridViewCellBorderStyle [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcellborderstyle
(VS.80).aspx ]
DataGridViewHeaderBorderStyle [ http://msdn2.microsoft.com/en-
us/library/wcd876d6(VS.80).aspx ]
Other Resources
Basic Formatting and Styling in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/ms171598(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/ehz9ksfa(vs.80,d=printer).aspx 5/22/2007
Cell Styles in the Windows Forms DataGridView Control Page 1 of 11
http://msdn2.microsoft.com/en-us/library/1yef90x0(vs.80,d=printer).aspx 5/22/2007
Cell Styles in the Windows Forms DataGridView Control Page 2 of 11
us/library/system.windows.forms.datagridviewcellstyle.formatprovider
(VS.80).aspx ]
z NullValue [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcellstyle.nullvalue
(VS.80).aspx ] and DataSourceNullValue
[ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcellstyle.datasourcenullvalue
(VS.80).aspx ]
z WrapMode [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcellstyle.wrapmode
(VS.80).aspx ]
z Alignment [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcellstyle.alignment
(VS.80).aspx ]
z Padding [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcellstyle.padding
(VS.80).aspx ]
For more information on these properties and other cell-style properties,
see the DataGridViewCellStyle reference documentation and the topics
listed in the See Also section below.
http://msdn2.microsoft.com/en-us/library/1yef90x0(vs.80,d=printer).aspx 5/22/2007
Cell Styles in the Windows Forms DataGridView Control Page 3 of 11
Property Classes D
DefaultCellStyle DataGridView, G
DataGridViewColumn, s
DataGridViewRow, d
and derived classes s
u
c
e
c
(
h
c
c
in
http://msdn2.microsoft.com/en-us/library/1yef90x0(vs.80,d=printer).aspx 5/22/2007
Cell Styles in the Windows Forms DataGridView Control Page 4 of 11
(VS.80).aspx ] d
s
u
t
c
c
h
O
b
c
t
v
s
e
InheritedStyle DataGridViewCell, G
DataGridViewRow, t
DataGridViewColumn, c
and derived classes a
t
r
c
in
s
in
f
h
le
http://msdn2.microsoft.com/en-us/library/1yef90x0(vs.80,d=printer).aspx 5/22/2007
Cell Styles in the Windows Forms DataGridView Control Page 5 of 11
Style Inheritance
http://msdn2.microsoft.com/en-us/library/1yef90x0(vs.80,d=printer).aspx 5/22/2007
Cell Styles in the Windows Forms DataGridView Control Page 6 of 11
order.
1. System.Windows.Forms.DataGridViewCell.Style
2. System.Windows.Forms.DataGridView.ColumnHeadersDefaultCellS
or
System.Windows.Forms.DataGridView.RowHeadersDefaultCellStyle
3. System.Windows.Forms.DataGridView.DefaultCellStyle
The following diagram illustrates this process.
You can also access the styles inherited by specific rows and columns. The
column InheritedStyle [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcolumn.inheritedstyle
(VS.80).aspx ] property inherits its values from the following properties.
1. System.Windows.Forms.DataGridViewColumn.DefaultCellStyle
2. System.Windows.Forms.DataGridView.DefaultCellStyle
The row InheritedStyle [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewrow.inheritedstyle
(VS.80).aspx ] property inherits its values from the following properties.
1. System.Windows.Forms.DataGridViewRow.DefaultCellStyle
2. System.Windows.Forms.DataGridView.AlternatingRowsDefaultCellS
(only for cells in rows with odd index numbers)
http://msdn2.microsoft.com/en-us/library/1yef90x0(vs.80,d=printer).aspx 5/22/2007
Cell Styles in the Windows Forms DataGridView Control Page 7 of 11
3. System.Windows.Forms.DataGridView.RowsDefaultCellStyle
4. System.Windows.Forms.DataGridView.DefaultCellStyle
For each property in a DataGridViewCellStyle object returned by an
InheritedStyle property, the property value is obtained from the first cell
style in the appropriate list that has the corresponding property set to a
value other than the DataGridViewCellStyle class defaults.
The following table illustrates how the ForeColor property value for an
example cell is inherited from its containing column.
Example ForeColor value
Property of type DataGridViewCellStyle object
System.Windows.Forms.DataGridViewCell.Style System.Drawing.Color.Emp
[ http://msdn2.microsoft.c
us/library/system.drawing.
(VS.80).aspx ]
System.Windows.Forms.DataGridViewRow.DefaultCellStyle System.Drawing.Color.Red
[ http://msdn2.microsoft.c
us/library/system.drawing.
(VS.80).aspx ]
System.Windows.Forms.DataGridView.AlternatingRowsDefaultCellStyle System.Drawing.Color.E
System.Windows.Forms.DataGridView.RowsDefaultCellStyle System.Drawing.Color.E
System.Windows.Forms.DataGridViewColumn.DefaultCellStyle System.Drawing.Color.Dark
[ http://msdn2.microsoft.c
us/library/system.drawing.
(VS.80).aspx ]
System.Windows.Forms.DataGridView.DefaultCellStyle System.Drawing.Color.Blac
[ http://msdn2.microsoft.c
us/library/system.drawing.
(VS.80).aspx ]
http://msdn2.microsoft.com/en-us/library/1yef90x0(vs.80,d=printer).aspx 5/22/2007
Cell Styles in the Windows Forms DataGridView Control Page 8 of 11
If visual styles are enabled, the row and column headers (except for the TopLeftHeaderCell
[ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview.topleftheadercell
(VS.80).aspx ] ) are automatically styled by the current theme, overriding any styles specified by
these properties.
http://msdn2.microsoft.com/en-us/library/1yef90x0(vs.80,d=printer).aspx 5/22/2007
Cell Styles in the Windows Forms DataGridView Control Page 9 of 11
You can also dynamically modify the styles of individual cells in response to
events such as the System.Windows.Forms.DataGridView.CellMouseEnter
[ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.cellmouseenter
(VS.80).aspx ] and CellMouseLeave [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.cellmouseleave
(VS.80).aspx ] events. For example, in a handler for the CellMouseEnter
event, you could store the current value of the cell background color
(retrieved through the cell's Style property), then set it to a new color that
will highlight the cell when the mouse hovers over it. In a handler for the
CellMouseLeave event, you can then restore the background color to the
original value.
Note
Caching the values stored in the cell's Style property is important regardless of whether a particular
style value is set. If you temporarily replace a style setting, restoring it to its original "not set" state
ensures that the cell will go back to inheriting the style setting from a higher level. If you need to
http://msdn2.microsoft.com/en-us/library/1yef90x0(vs.80,d=printer).aspx 5/22/2007
Cell Styles in the Windows Forms DataGridView Control Page 10 of 11
determine the actual style in effect for a cell regardless of whether the style is inherited, use the cell's
InheritedStyle property.
See Also
Tasks
How to: Set Default Cell Styles for the Windows Forms DataGridView
Control [ http://msdn2.microsoft.com/en-us/library/k4sab6f9
(VS.80).aspx ]
Reference
DataGridView [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview(VS.80).aspx ]
DataGridViewCellStyle [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcellstyle(VS.80).aspx ]
System.Windows.Forms.DataGridView.AlternatingRowsDefaultCellStyle
[ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.alternatingrowsdefaultcellstyle
(VS.80).aspx ]
System.Windows.Forms.DataGridView.ColumnHeadersDefaultCellStyle
[ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.columnheadersdefaultcellstyle
(VS.80).aspx ]
System.Windows.Forms.DataGridView.DefaultCellStyle
[ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.defaultcellstyle
(VS.80).aspx ]
System.Windows.Forms.DataGridView.RowHeadersDefaultCellStyle
[ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.rowheadersdefaultcellstyle
(VS.80).aspx ]
System.Windows.Forms.DataGridView.RowsDefaultCellStyle
[ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.rowsdefaultcellstyle
(VS.80).aspx ]
System.Windows.Forms.DataGridViewBand.InheritedStyle
[ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewband.inheritedstyle
(VS.80).aspx ]
System.Windows.Forms.DataGridViewRow.InheritedStyle
[ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewrow.inheritedstyle
(VS.80).aspx ]
System.Windows.Forms.DataGridViewColumn.InheritedStyle
[ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcolumn.inheritedstyle
(VS.80).aspx ]
http://msdn2.microsoft.com/en-us/library/1yef90x0(vs.80,d=printer).aspx 5/22/2007
Cell Styles in the Windows Forms DataGridView Control Page 11 of 11
System.Windows.Forms.DataGridViewBand.DefaultCellStyle
[ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewband.defaultcellstyle
(VS.80).aspx ]
System.Windows.Forms.DataGridViewCell.InheritedStyle
[ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcell.inheritedstyle
(VS.80).aspx ]
System.Windows.Forms.DataGridViewCell.Style
[ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcell.style(VS.80).aspx ]
System.Windows.Forms.DataGridView.CellFormatting
[ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.cellformatting
(VS.80).aspx ]
System.Windows.Forms.DataGridView.CellStyleContentChanged
[ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.cellstylecontentchanged
(VS.80).aspx ]
System.Windows.Forms.DataGridView.RowPrePaint
[ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.rowprepaint(VS.80).aspx ]
System.Windows.Forms.DataGridView.RowPostPaint
[ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.rowpostpaint(VS.80).aspx ]
Concepts
Data Formatting in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/hezscd0d(VS.80).aspx ]
Other Resources
Basic Formatting and Styling in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/ms171598(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/1yef90x0(vs.80,d=printer).aspx 5/22/2007
How to: Set Default Cell Styles for the Windows Forms DataGridView Control Page 1 of 5
Me.dataGridView1.DefaultCellStyle.BackColor = Color.Beige
Me.dataGridView1.DefaultCellStyle.Font = New Font("Tahoma", 12
Copy Code
http://msdn2.microsoft.com/en-us/library/k4sab6f9(vs.80,d=printer).aspx 5/22/2007
How to: Set Default Cell Styles for the Windows Forms DataGridView Control Page 2 of 5
C#
this.dataGridView1.DefaultCellStyle.BackColor = Color.Beige;
this.dataGridView1.DefaultCellStyle.Font = new Font("Tahoma",
C# Copy Code
With Me.dataGridView1
.Rows(3).DefaultCellStyle = highlightCellStyle
.Rows(8).DefaultCellStyle = highlightCellStyle
.Columns("UnitPrice").DefaultCellStyle = currencyCellStyle
.Columns("TotalPrice").DefaultCellStyle = currencyCellStyl
End With
C# Copy Code
this.dataGridView1.Rows[3].DefaultCellStyle = highlightCellSty
this.dataGridView1.Rows[8].DefaultCellStyle = highlightCellSty
this.dataGridView1.Columns["UnitPrice"].DefaultCellStyle =
currencyCellStyle;
this.dataGridView1.Columns["TotalPrice"].DefaultCellStyle =
http://msdn2.microsoft.com/en-us/library/k4sab6f9(vs.80,d=printer).aspx 5/22/2007
How to: Set Default Cell Styles for the Windows Forms DataGridView Control Page 3 of 5
currencyCellStyle;
Example
With Me.dataGridView1
.DefaultCellStyle.BackColor = Color.Beige
.DefaultCellStyle.Font = New Font("Tahoma", 12)
.Rows(3).DefaultCellStyle = highlightCellStyle
.Rows(8).DefaultCellStyle = highlightCellStyle
.Columns("UnitPrice").DefaultCellStyle = currencyCellSty
.Columns("TotalPrice").DefaultCellStyle = currencyCellSt
End With
End Sub
C# Copy Code
private void SetDefaultCellStyles()
{
this.dataGridView1.DefaultCellStyle.BackColor = Color.Beige;
this.dataGridView1.DefaultCellStyle.Font = new Font("Tahoma"
this.dataGridView1.Rows[3].DefaultCellStyle = highlightCellS
this.dataGridView1.Rows[8].DefaultCellStyle = highlightCellS
this.dataGridView1.Columns["UnitPrice"].DefaultCellStyle =
currencyCellStyle;
this.dataGridView1.Columns["TotalPrice"].DefaultCellStyle =
currencyCellStyle;
}
http://msdn2.microsoft.com/en-us/library/k4sab6f9(vs.80,d=printer).aspx 5/22/2007
How to: Set Default Cell Styles for the Windows Forms DataGridView Control Page 4 of 5
Robust Programming
To achieve maximum scalability when you work with very large data
sets, you should share DataGridViewCellStyle objects across multiple
rows, columns, or cells that use the same styles, rather than set the
style properties for individual elements separately. Additionally, you
should create shared rows and access them by using the
System.Windows.Forms.DataGridViewRowCollection.SharedRow
(System.Int32) [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewrowcollection.sharedrow
(VS.80).aspx ] property. For more information, see Best Practices for
Scaling the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/ha5xt0d9(VS.80).aspx ] .
See Also
Tasks
How to: Set Alternating Row Styles for the Windows Forms DataGridView
Control [ http://msdn2.microsoft.com/en-us/library/txth0a6h
(VS.80).aspx ]
Reference
DataGridView [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview(VS.80).aspx ]
DataGridViewCellStyle [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcellstyle(VS.80).aspx ]
System.Windows.Forms.DataGridView.DefaultCellStyle
[ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.defaultcellstyle
(VS.80).aspx ]
System.Windows.Forms.DataGridViewBand.DefaultCellStyle
[ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewband.defaultcellstyle
(VS.80).aspx ]
Concepts
Cell Styles in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/1yef90x0(VS.80).aspx ]
Best Practices for Scaling the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/ha5xt0d9(VS.80).aspx ]
Other Resources
http://msdn2.microsoft.com/en-us/library/k4sab6f9(vs.80,d=printer).aspx 5/22/2007
How to: Set Default Cell Styles for the Windows Forms DataGridView Control Page 5 of 5
Community Content
http://msdn2.microsoft.com/en-us/library/k4sab6f9(vs.80,d=printer).aspx 5/22/2007
How to: Format Data in the Windows Forms DataGridView Control Page 1 of 4
C# Copy Code
this.dataGridView1.Columns["UnitPrice"].DefaultCellStyle.Format
this.dataGridView1.Columns["ShipDate"].DefaultCellStyle.Format =
http://msdn2.microsoft.com/en-us/library/f9x2790s(vs.80,d=printer).aspx 5/22/2007
How to: Format Data in the Windows Forms DataGridView Control Page 2 of 4
C# Copy Code
this.dataGridView1.DefaultCellStyle.NullValue = "no entry";
C# Copy Code
this.dataGridView1.DefaultCellStyle.WrapMode =
DataGridViewTriState.True;
http://msdn2.microsoft.com/en-us/library/f9x2790s(vs.80,d=printer).aspx 5/22/2007
How to: Format Data in the Windows Forms DataGridView Control Page 3 of 4
C# Copy Code
this.dataGridView1.Columns["CustomerName"].DefaultCellStyle
.Alignment = DataGridViewContentAlignment.MiddleRight;
Example
C# Copy Code
private void SetFormatting()
{
this.dataGridView1.Columns["UnitPrice"].DefaultCellStyle.For
this.dataGridView1.Columns["ShipDate"].DefaultCellStyle.Form
this.dataGridView1.Columns["CustomerName"].DefaultCellStyle
.Alignment = DataGridViewContentAlignment.MiddleRight;
this.dataGridView1.DefaultCellStyle.NullValue = "no entry";
this.dataGridView1.DefaultCellStyle.WrapMode =
DataGridViewTriState.True;
}
http://msdn2.microsoft.com/en-us/library/f9x2790s(vs.80,d=printer).aspx 5/22/2007
How to: Format Data in the Windows Forms DataGridView Control Page 4 of 4
(VS.80).aspx ] assemblies.
Robust Programming
See Also
Tasks
How to: Customize Data Formatting in the Windows Forms DataGridView
Control [ http://msdn2.microsoft.com/en-us/library/z1cc356h
(VS.80).aspx ]
Reference
System.Windows.Forms.DataGridView.DefaultCellStyle
[ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.defaultcellstyle
(VS.80).aspx ]
System.Windows.Forms.DataGridViewBand.DefaultCellStyle
[ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewband.defaultcellstyle
(VS.80).aspx ]
DataGridViewCellStyle [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcellstyle(VS.80).aspx ]
Concepts
Cell Styles in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/1yef90x0(VS.80).aspx ]
Data Formatting in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/hezscd0d(VS.80).aspx ]
Other Resources
Basic Formatting and Styling in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/ms171598(VS.80).aspx ]
Formatting Types [ http://msdn2.microsoft.com/en-us/library/fbxft59x
(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/f9x2790s(vs.80,d=printer).aspx 5/22/2007
How to: Set Alternating Row Styles for the Windows Forms DataGridView Control Page 1 of 3
C# Copy Code
this.dataGridView1.RowsDefaultCellStyle.BackColor = Color.Bisque
http://msdn2.microsoft.com/en-us/library/txth0a6h(vs.80,d=printer).aspx 5/22/2007
How to: Set Alternating Row Styles for the Windows Forms DataGridView Control Page 2 of 3
this.dataGridView1.AlternatingRowsDefaultCellStyle.BackColor =
Color.Beige;
Note
Robust Programming
See Also
Tasks
How to: Set Font and Color Styles in the Windows Forms DataGridView
Control [ http://msdn2.microsoft.com/en-us/library/z2akwyy7
(VS.80).aspx ]
Reference
System.Windows.Forms.DataGridView.AlternatingRowsDefaultCellStyle
[ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.alternatingrowsdefaultcellstyle
(VS.80).aspx ]
System.Windows.Forms.DataGridView.RowsDefaultCellStyle
[ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.rowsdefaultcellstyle
(VS.80).aspx ]
DataGridView [ http://msdn2.microsoft.com/en-
http://msdn2.microsoft.com/en-us/library/txth0a6h(vs.80,d=printer).aspx 5/22/2007
How to: Set Alternating Row Styles for the Windows Forms DataGridView Control Page 3 of 3
us/library/system.windows.forms.datagridview(VS.80).aspx ]
DataGridViewCellStyle [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcellstyle(VS.80).aspx ]
Concepts
Cell Styles in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/1yef90x0(VS.80).aspx ]
Best Practices for Scaling the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/ha5xt0d9(VS.80).aspx ]
Other Resources
Basic Formatting and Styling in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/ms171598(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/txth0a6h(vs.80,d=printer).aspx 5/22/2007
How to: Use the Row Template to Customize Rows in the Windows Forms DataGridVie... Page 1 of 3
The row template is used only when rows are added. You cannot change existing rows by changing the
row template.
http://msdn2.microsoft.com/en-us/library/d2bkk9d1(vs.80,d=printer).aspx 5/22/2007
How to: Use the Row Template to Customize Rows in the Windows Forms DataGridVie... Page 2 of 3
[ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.rowtemplate
(VS.80).aspx ] property.
C# Copy Code
DataGridViewRow row = this.dataGridView1.RowTemplate;
row.DefaultCellStyle.BackColor = Color.Bisque;
row.Height = 35;
row.MinimumHeight = 20;
See Also
Reference
DataGridView [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview(VS.80).aspx ]
DataGridViewCellStyle [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcellstyle(VS.80).aspx ]
DataGridViewRow [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewrow(VS.80).aspx ]
System.Windows.Forms.DataGridView.RowTemplate
http://msdn2.microsoft.com/en-us/library/d2bkk9d1(vs.80,d=printer).aspx 5/22/2007
How to: Use the Row Template to Customize Rows in the Windows Forms DataGridVie... Page 3 of 3
[ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.rowtemplate(VS.80).aspx ]
Concepts
Cell Styles in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/1yef90x0(VS.80).aspx ]
Other Resources
Basic Formatting and Styling in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/ms171598(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/d2bkk9d1(vs.80,d=printer).aspx 5/22/2007
Data Display Modes in the Windows Forms DataGridView Control Page 1 of 2
Unbound
Unbound mode is suitable for displaying relatively small amounts of data that you manage
programmatically. You do not attach the DataGridView control directly to a data source as in bound mode.
Instead, you must populate the control yourself, typically by using the
System.Windows.Forms.DataGridViewRowCollection.Add [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewrowcollection.add(VS.80).aspx ] method.
Unbound mode can be particularly useful for static, read-only data, or when you want to provide your own
code that interacts with an external data store. When you want your users to interact with an external data
source, however, you will typically use bound mode.
For an example that uses a read-only unbound DataGridView, see How to: Create an Unbound Windows
Forms DataGridView Control [ http://msdn2.microsoft.com/en-us/library/zf3zx9fy(VS.80).aspx ] .
Bound
Bound mode is suitable for managing data using automatic interaction with the data store. You can attach
the DataGridView control directly to its data source by setting the DataSource
[ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview.datasource(VS.80).aspx ]
property. When the control is data bound, data rows are pushed and pulled without the need of explicit
management on your part. When the AutoGenerateColumns [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.autogeneratecolumns(VS.80).aspx ] property is true, each
column in your data source will cause a corresponding column to be created in the control. If you prefer to
create your own columns, you can set this property to false and use the DataPropertyName
[ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridviewcolumn.datapropertyname
(VS.80).aspx ] property to bind each column when you configure it. This is useful when you want to use a
column type other than the types that are generated by default. For more information, see Column Types in
the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-us/library/bxt3k60s
(VS.80).aspx ] .
For an example that uses a bound DataGridView control, see Walkthrough: Validating Data in the
Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-us/library/ykdxa0bc
(VS.80).aspx ] .
You can also add unbound columns to a DataGridView control in bound mode. This is useful when you
want to display a column of buttons or links that enable users to perform actions on specific rows. It is also
useful to display columns with values calculated from bound columns. You can populate the cell values for
calculated columns in a handler for the CellFormatting [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.cellformatting(VS.80).aspx ] event. If you are using a
DataSet [ http://msdn2.microsoft.com/en-us/library/system.data.dataset(VS.80).aspx ] or DataTable
[ http://msdn2.microsoft.com/en-us/library/system.data.datatable(VS.80).aspx ] as the data source,
however, you might want to use the System.Data.DataColumn.Expression
[ http://msdn2.microsoft.com/en-us/library/system.data.datacolumn.expression(VS.80).aspx ] property to
create a calculated column instead. In this case, the DataGridView control will treat calculated column just
like any other column in the data source.
Sorting by unbound columns in bound mode is not supported. If you create an unbound column in bound
mode that contains user-editable values, you must implement virtual mode to maintain these values when
the control is sorted by a bound column.
Virtual
http://msdn2.microsoft.com/en-us/library/cd28yf6d(vs.80,d=printer).aspx 5/23/2007
Data Display Modes in the Windows Forms DataGridView Control Page 2 of 2
With virtual mode, you can implement your own data management operations. This is necessary to
maintain the values of unbound columns in bound mode when the control is sorted by bound columns. The
primary use of virtual mode, however, is to optimize performance when interacting with large amounts of
data.
You attach the DataGridView control to a cache that you manage, and your code controls when data rows
are pushed and pulled. To keep the memory footprint small, the cache should be similar in size to the
number of rows currently displayed. When the user scrolls new rows into view, your code requests new
data from the cache and optionally flushes old data from memory.
When you are implementing virtual mode, you will need to track when a new row is needed in the data
model and when to rollback the addition of the new row. The exact implementation of this functionality will
depend on the implementation of the data model and the transaction semantics of the data model; whether
commit scope is at the cell or row level.
For more information about virtual mode, see Virtual Mode in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/ms171622(VS.80).aspx ] . For an example that shows how to
use virtual mode events, see Walkthrough: Implementing Virtual Mode in the Windows Forms DataGridView
Control [ http://msdn2.microsoft.com/en-us/library/15a31akc(VS.80).aspx ] .
See Also
Tasks
Walkthrough: Creating an Unbound Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/5s3ce6k8(VS.80).aspx ]
How to: Bind Data to the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/fbk67b6z(VS.80).aspx ]
Walkthrough: Implementing Virtual Mode in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/15a31akc(VS.80).aspx ]
Reference
DataGridView [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview
(VS.80).aspx ]
System.Windows.Forms.DataGridView.DataSource [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.datasource(VS.80).aspx ]
System.Windows.Forms.DataGridView.VirtualMode [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.virtualmode(VS.80).aspx ]
BindingSource [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.bindingsource
(VS.80).aspx ]
System.Windows.Forms.DataGridViewColumn.DataPropertyName [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcolumn.datapropertyname(VS.80).aspx ]
Concepts
Column Types in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/bxt3k60s(VS.80).aspx ]
Virtual Mode in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/ms171622(VS.80).aspx ]
Other Resources
Displaying Data in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/ms171600(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/cd28yf6d(vs.80,d=printer).aspx 5/23/2007
Data Formatting in the Windows Forms DataGridView Control Page 1 of 2
The DataGridView control provides basic data formatting of cell values through the DataGridViewCellStyle
[ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridviewcellstyle(VS.80).aspx ]
class. You can use the Format [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcellstyle.format(VS.80).aspx ] property to format date, time,
number, and enumeration values for the current default culture using the format specifiers described in
Formatting Types [ http://msdn2.microsoft.com/en-us/library/fbxft59x(VS.80).aspx ] . You can also format
these values for specific cultures using the FormatProvider [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcellstyle.formatprovider(VS.80).aspx ] property. The
specified format is used both to display data and to parse data that the user enters in the specified format.
The DataGridViewCellStyle class provides additional formatting properties for wordwrap, text alignment,
and the custom display of null database values. For more information, see How to: Format Data in the
Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-us/library/f9x2790s
(VS.80).aspx ] .
If the basic formatting does not meet your needs, you can provide custom data formatting in a handler for
the System.Windows.Forms.DataGridView.CellFormatting [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.cellformatting(VS.80).aspx ] event. The
DataGridViewCellFormattingEventArgs [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcellformattingeventargs(VS.80).aspx ] passed to the handler
has a Value [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.converteventargs.value
(VS.80).aspx ] property that initially contains the cell value. Normally, this value is automatically converted
to the display type. To convert the value yourself, set the Value property to a value of the display type.
Note
If a format string is in effect for the cell, it overrides your change of the Value property value unless
you set the FormattingApplied [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcellformattingeventargs.formattingapplied
(VS.80).aspx ] property to true.
The CellFormatting event is also useful when you want to set DataGridViewCellStyle properties for
individual cells based on their values. For more information, see How to: Customize Data Formatting in the
Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-us/library/z1cc356h
(VS.80).aspx ] .
If the default parsing of user-specified values does not meet your needs, you can handle the CellParsing
[ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview.cellparsing(VS.80).aspx ]
event of the DataGridView control to provide custom parsing.
See Also
Tasks
How to: Format Data in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/f9x2790s(VS.80).aspx ]
http://msdn2.microsoft.com/en-us/library/hezscd0d(vs.80,d=printer).aspx 5/23/2007
Data Formatting in the Windows Forms DataGridView Control Page 2 of 2
How to: Customize Data Formatting in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/z1cc356h(VS.80).aspx ]
Reference
DataGridView [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview
(VS.80).aspx ]
DataGridViewCellStyle [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcellstyle(VS.80).aspx ]
Concepts
Cell Styles in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/1yef90x0(VS.80).aspx ]
Other Resources
Displaying Data in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/ms171600(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/hezscd0d(vs.80,d=printer).aspx 5/23/2007
Walkthrough: Creating an Unbound Windows Forms DataGridView Control Page 1 of 9
To copy the code in this topic as a single listing, see How to: Create an Unbound Windows Forms
DataGridView Control [ http://msdn2.microsoft.com/en-us/library/zf3zx9fy(VS.80).aspx ] .
Imports System
Imports System.Drawing
Imports System.Windows.Forms
End Class
C# Copy Code
using System;
using System.Drawing;
using System.Windows.Forms;
http://msdn2.microsoft.com/en-us/library/5s3ce6k8(vs.80,d=printer).aspx 5/23/2007
Walkthrough: Creating an Unbound Windows Forms DataGridView Control Page 2 of 9
2. Implement a SetupLayout method in your form's class definition to set up the form's layout.
With addNewRowButton
.Text = "Add Row"
.Location = New Point(10, 10)
End With
With deleteRowButton
.Text = "Delete Row"
.Location = New Point(100, 10)
End With
With buttonPanel
.Controls.Add(addNewRowButton)
.Controls.Add(deleteRowButton)
.Height = 50
.Dock = DockStyle.Bottom
End With
Me.Controls.Add(Me.buttonPanel)
End Sub
C# Copy Code
buttonPanel.Controls.Add(addNewRowButton);
buttonPanel.Controls.Add(deleteRowButton);
buttonPanel.Height = 50;
http://msdn2.microsoft.com/en-us/library/5s3ce6k8(vs.80,d=printer).aspx 5/23/2007
Walkthrough: Creating an Unbound Windows Forms DataGridView Control Page 3 of 9
buttonPanel.Dock = DockStyle.Bottom;
this.Controls.Add(this.buttonPanel);
}
Me.Controls.Add(songsDataGridView)
songsDataGridView.ColumnCount = 5
With songsDataGridView.ColumnHeadersDefaultCellStyle
.BackColor = Color.Navy
.ForeColor = Color.White
.Font = New Font(songsDataGridView.Font, FontStyle.Bold)
End With
With songsDataGridView
.Name = "songsDataGridView"
.Location = New Point(8, 8)
.Size = New Size(500, 250)
.AutoSizeRowsMode = _
DataGridViewAutoSizeRowsMode.DisplayedCellsExceptHeaders
.ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.Single
.CellBorderStyle = DataGridViewCellBorderStyle.Single
.GridColor = Color.Black
.RowHeadersVisible = False
.SelectionMode = DataGridViewSelectionMode.FullRowSelect
http://msdn2.microsoft.com/en-us/library/5s3ce6k8(vs.80,d=printer).aspx 5/23/2007
Walkthrough: Creating an Unbound Windows Forms DataGridView Control Page 4 of 9
.MultiSelect = False
.Dock = DockStyle.Fill
End With
End Sub
C# Copy Code
songsDataGridView.ColumnCount = 5;
songsDataGridView.ColumnHeadersDefaultCellStyle.BackColor = Color.Navy;
songsDataGridView.ColumnHeadersDefaultCellStyle.ForeColor = Color.White;
songsDataGridView.ColumnHeadersDefaultCellStyle.Font =
new Font(songsDataGridView.Font, FontStyle.Bold);
songsDataGridView.Name = "songsDataGridView";
songsDataGridView.Location = new Point(8, 8);
songsDataGridView.Size = new Size(500, 250);
songsDataGridView.AutoSizeRowsMode =
DataGridViewAutoSizeRowsMode.DisplayedCellsExceptHeaders;
songsDataGridView.ColumnHeadersBorderStyle =
DataGridViewHeaderBorderStyle.Single;
songsDataGridView.CellBorderStyle = DataGridViewCellBorderStyle.Single;
songsDataGridView.GridColor = Color.Black;
songsDataGridView.RowHeadersVisible = false;
songsDataGridView.SelectionMode =
DataGridViewSelectionMode.FullRowSelect;
songsDataGridView.MultiSelect = false;
songsDataGridView.Dock = DockStyle.Fill;
songsDataGridView.CellFormatting += new
DataGridViewCellFormattingEventHandler(
songsDataGridView_CellFormatting);
}
http://msdn2.microsoft.com/en-us/library/5s3ce6k8(vs.80,d=printer).aspx 5/23/2007
Walkthrough: Creating an Unbound Windows Forms DataGridView Control Page 5 of 9
With Me.songsDataGridView.Rows
.Add(row0)
.Add(row1)
.Add(row2)
.Add(row3)
.Add(row4)
.Add(row5)
.Add(row6)
End With
With Me.songsDataGridView
.Columns(0).DisplayIndex = 3
.Columns(1).DisplayIndex = 4
.Columns(2).DisplayIndex = 0
.Columns(3).DisplayIndex = 1
.Columns(4).DisplayIndex = 2
End With
End Sub
C# Copy Code
songsDataGridView.Rows.Add(row0);
songsDataGridView.Rows.Add(row1);
songsDataGridView.Rows.Add(row2);
songsDataGridView.Rows.Add(row3);
songsDataGridView.Rows.Add(row4);
http://msdn2.microsoft.com/en-us/library/5s3ce6k8(vs.80,d=printer).aspx 5/23/2007
Walkthrough: Creating an Unbound Windows Forms DataGridView Control Page 6 of 9
songsDataGridView.Rows.Add(row5);
songsDataGridView.Rows.Add(row6);
songsDataGridView.Columns[0].DisplayIndex = 3;
songsDataGridView.Columns[1].DisplayIndex = 4;
songsDataGridView.Columns[2].DisplayIndex = 0;
songsDataGridView.Columns[3].DisplayIndex = 1;
songsDataGridView.Columns[4].DisplayIndex = 2;
}
5. With the utility methods in place, you can attach event handlers.
You will handle the Add and Delete buttons' Click [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.control.click(VS.80).aspx ] events, the form's Load
[ http://msdn2.microsoft.com/en-us/library/system.windows.forms.form.load(VS.80).aspx ]
event, and the DataGridView control's CellFormatting [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.cellformatting(VS.80).aspx ] event.
When the Add button's Click event is raised, a new, empty row is added to the DataGridView.
When the Delete button's Click event is raised, the selected row is deleted, unless it is the row
for new records, which enables the user add new rows. This row is always the last row in the
DataGridView control.
When the form's Load event is raised, the SetupLayout, SetupDataGridView, and
PopulateDataGridView utility methods are called.
When the CellFormatting event is raised, each cell in the Date column is formatted as a long
date, unless the cell's value cannot be parsed.
SetupLayout()
SetupDataGridView()
PopulateDataGridView()
End Sub
If Me.songsDataGridView.Columns(e.ColumnIndex).Name = _
"Release Date" Then
End If
http://msdn2.microsoft.com/en-us/library/5s3ce6k8(vs.80,d=printer).aspx 5/23/2007
Walkthrough: Creating an Unbound Windows Forms DataGridView Control Page 7 of 9
End Sub
Me.songsDataGridView.Rows.Add()
End Sub
Me.songsDataGridView.Rows.RemoveAt( _
Me.songsDataGridView.SelectedRows(0).Index)
End If
End Sub
C# Copy Code
public Form1()
{
this.Load += new EventHandler(Form1_Load);
}
http://msdn2.microsoft.com/en-us/library/5s3ce6k8(vs.80,d=printer).aspx 5/23/2007
Walkthrough: Creating an Unbound Windows Forms DataGridView Control Page 8 of 9
}
}
}
You will see a DataGridView control that displays the songs listed in PopulateDataGridView. You
can add new rows with the Add Row button, and you can delete selected rows with the Delete
Row button. The unbound DataGridView control is the data store, and its data is independent of
any external source, such as a DataSet [ http://msdn2.microsoft.com/en-
us/library/system.data.dataset(VS.80).aspx ] or an array.
Next Steps
This application gives you a basic understanding of the DataGridView control's capabilities. You can
customize the appearance and behavior of the DataGridView control in several ways:
z Change border and header styles. For more information, see How to: Change the Border and
Gridline Styles in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/ehz9ksfa(VS.80).aspx ] .
z Enable or restrict user input to the DataGridView control. For more information, see How to:
Prevent Row Addition and Deletion in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/61bk13ye(VS.80).aspx ] , and How to: Make Columns
Read-Only in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/cze614bb(VS.80).aspx ] .
z Check user input for database-related errors. For more information, see Walkthrough: Handling
Errors that Occur During Data Entry in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/t4a23xx4(VS.80).aspx ] .
z Handle very large data sets using virtual mode. For more information, see Walkthrough:
Implementing Virtual Mode in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/15a31akc(VS.80).aspx ] .
z Customize the appearance of cells. For more information, see How to: Customize the Appearance
of Cells in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/hta8z9sz(VS.80).aspx ] and How to: Set Default Cell Styles for the Windows Forms
DataGridView Control [ http://msdn2.microsoft.com/en-us/library/k4sab6f9(VS.80).aspx ] .
See Also
Tasks
How to: Create an Unbound Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/zf3zx9fy(VS.80).aspx ]
Reference
DataGridView [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview
http://msdn2.microsoft.com/en-us/library/5s3ce6k8(vs.80,d=printer).aspx 5/23/2007
Walkthrough: Creating an Unbound Windows Forms DataGridView Control Page 9 of 9
(VS.80).aspx ]
Concepts
Data Display Modes in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/cd28yf6d(VS.80).aspx ]
Other Resources
Displaying Data in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/ms171600(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/5s3ce6k8(vs.80,d=printer).aspx 5/23/2007
How to: Create an Unbound Windows Forms DataGridView Control Page 1 of 6
For a complete explanation of this code example, see Walkthrough: Creating an Unbound Windows Forms
DataGridView Control [ http://msdn2.microsoft.com/en-us/library/5s3ce6k8(VS.80).aspx ] .
Example
Imports System
Imports System.Drawing
Imports System.Windows.Forms
SetupLayout()
SetupDataGridView()
PopulateDataGridView()
End Sub
If Me.songsDataGridView.Columns(e.ColumnIndex).Name = _
"Release Date" Then
End If
End Sub
Me.songsDataGridView.Rows.Add()
End Sub
http://msdn2.microsoft.com/en-us/library/zf3zx9fy(vs.80,d=printer).aspx 5/23/2007
How to: Create an Unbound Windows Forms DataGridView Control Page 2 of 6
Me.songsDataGridView.Rows.RemoveAt( _
Me.songsDataGridView.SelectedRows(0).Index)
End If
End Sub
With addNewRowButton
.Text = "Add Row"
.Location = New Point(10, 10)
End With
With deleteRowButton
.Text = "Delete Row"
.Location = New Point(100, 10)
End With
With buttonPanel
.Controls.Add(addNewRowButton)
.Controls.Add(deleteRowButton)
.Height = 50
.Dock = DockStyle.Bottom
End With
Me.Controls.Add(Me.buttonPanel)
End Sub
Me.Controls.Add(songsDataGridView)
songsDataGridView.ColumnCount = 5
With songsDataGridView.ColumnHeadersDefaultCellStyle
.BackColor = Color.Navy
.ForeColor = Color.White
.Font = New Font(songsDataGridView.Font, FontStyle.Bold)
End With
With songsDataGridView
.Name = "songsDataGridView"
.Location = New Point(8, 8)
.Size = New Size(500, 250)
.AutoSizeRowsMode = _
DataGridViewAutoSizeRowsMode.DisplayedCellsExceptHeaders
.ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.Single
.CellBorderStyle = DataGridViewCellBorderStyle.Single
.GridColor = Color.Black
.RowHeadersVisible = False
.SelectionMode = DataGridViewSelectionMode.FullRowSelect
.MultiSelect = False
.Dock = DockStyle.Fill
End With
End Sub
http://msdn2.microsoft.com/en-us/library/zf3zx9fy(vs.80,d=printer).aspx 5/23/2007
How to: Create an Unbound Windows Forms DataGridView Control Page 3 of 6
With Me.songsDataGridView.Rows
.Add(row0)
.Add(row1)
.Add(row2)
.Add(row3)
.Add(row4)
.Add(row5)
.Add(row6)
End With
With Me.songsDataGridView
.Columns(0).DisplayIndex = 3
.Columns(1).DisplayIndex = 4
.Columns(2).DisplayIndex = 0
.Columns(3).DisplayIndex = 1
.Columns(4).DisplayIndex = 2
End With
End Sub
<STAThreadAttribute()> _
Public Shared Sub Main()
Application.EnableVisualStyles()
Application.Run(New Form1())
End Sub
End Class
C# Copy Code
using System;
using System.Drawing;
using System.Windows.Forms;
public Form1()
{
this.Load += new EventHandler(Form1_Load);
}
http://msdn2.microsoft.com/en-us/library/zf3zx9fy(vs.80,d=printer).aspx 5/23/2007
How to: Create an Unbound Windows Forms DataGridView Control Page 4 of 6
{
Console.WriteLine("{0} is not a valid date.", e.Value.ToString());
}
}
}
}
}
buttonPanel.Controls.Add(addNewRowButton);
buttonPanel.Controls.Add(deleteRowButton);
buttonPanel.Height = 50;
buttonPanel.Dock = DockStyle.Bottom;
this.Controls.Add(this.buttonPanel);
}
songsDataGridView.ColumnCount = 5;
songsDataGridView.ColumnHeadersDefaultCellStyle.BackColor = Color.Navy;
songsDataGridView.ColumnHeadersDefaultCellStyle.ForeColor = Color.White;
songsDataGridView.ColumnHeadersDefaultCellStyle.Font =
new Font(songsDataGridView.Font, FontStyle.Bold);
songsDataGridView.Name = "songsDataGridView";
songsDataGridView.Location = new Point(8, 8);
songsDataGridView.Size = new Size(500, 250);
songsDataGridView.AutoSizeRowsMode =
DataGridViewAutoSizeRowsMode.DisplayedCellsExceptHeaders;
songsDataGridView.ColumnHeadersBorderStyle =
DataGridViewHeaderBorderStyle.Single;
songsDataGridView.CellBorderStyle = DataGridViewCellBorderStyle.Single;
songsDataGridView.GridColor = Color.Black;
songsDataGridView.RowHeadersVisible = false;
songsDataGridView.SelectionMode =
DataGridViewSelectionMode.FullRowSelect;
songsDataGridView.MultiSelect = false;
songsDataGridView.Dock = DockStyle.Fill;
songsDataGridView.CellFormatting += new
DataGridViewCellFormattingEventHandler(
http://msdn2.microsoft.com/en-us/library/zf3zx9fy(vs.80,d=printer).aspx 5/23/2007
How to: Create an Unbound Windows Forms DataGridView Control Page 5 of 6
songsDataGridView_CellFormatting);
}
songsDataGridView.Rows.Add(row0);
songsDataGridView.Rows.Add(row1);
songsDataGridView.Rows.Add(row2);
songsDataGridView.Rows.Add(row3);
songsDataGridView.Rows.Add(row4);
songsDataGridView.Rows.Add(row5);
songsDataGridView.Rows.Add(row6);
songsDataGridView.Columns[0].DisplayIndex = 3;
songsDataGridView.Columns[1].DisplayIndex = 4;
songsDataGridView.Columns[2].DisplayIndex = 0;
songsDataGridView.Columns[3].DisplayIndex = 1;
songsDataGridView.Columns[4].DisplayIndex = 2;
}
[STAThreadAttribute()]
static void Main()
{
Application.EnableVisualStyles();
Application.Run(new Form1());
}
}
For information about building this example from the command line for Visual Basic or Visual C#, see
Building from the Command Line (Visual Basic) [ http://msdn2.microsoft.com/en-us/library/25fz1td5
(VS.80).aspx ] or Command-Line Building [ http://msdn2.microsoft.com/en-us/library/78f4aasd
(VS.80).aspx ] . You can also build this example in Visual Studio by pasting the code into a new project.
For more information, see How to: Compile and Run a Complete Windows Forms Code Example Using
Visual Studio [ http://msdn2.microsoft.com/en-us/bb129228(vs.80).aspx ] and How to: Compile and
Run a Complete Windows Forms Code Example Using Visual Studio [ http://msdn2.microsoft.com/en-
us/bb129228(vs.90).aspx ] .
See Also
Tasks
Walkthrough: Creating an Unbound Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/5s3ce6k8(VS.80).aspx ]
Reference
DataGridView [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview
(VS.80).aspx ]
Concepts
Data Display Modes in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/cd28yf6d(VS.80).aspx ]
Other Resources
Displaying Data in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
http://msdn2.microsoft.com/en-us/library/zf3zx9fy(vs.80,d=printer).aspx 5/23/2007
How to: Create an Unbound Windows Forms DataGridView Control Page 6 of 6
us/library/ms171600(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/zf3zx9fy(vs.80,d=printer).aspx 5/23/2007
How to: Bind Data to the Windows Forms DataGridView Control Page 1 of 6
There is extensive support for this task in Visual Studio. For more information, see How to: Bind Data to the
Windows Forms DataGridView Control Using the Designer [ http://msdn2.microsoft.com/en-us/33w255ac
(vs.80).aspx ] and How to: Bind Data to the Windows Forms DataGridView Control Using the Designer
[ http://msdn2.microsoft.com/en-us/33w255ac(vs.90).aspx ] .
Procedure
1. Implement a method to handle the details of retrieving data from a database. The following code
example implements a GetData method that initializes a SqlDataAdapter
[ http://msdn2.microsoft.com/en-us/library/system.data.sqlclient.sqldataadapter(VS.80).aspx ]
component and uses it to populate a DataTable [ http://msdn2.microsoft.com/en-
us/library/system.data.datatable(VS.80).aspx ] . The DataTable is then bound to the
BindingSource component. Be sure to set the connectionString variable to a value that is
appropriate for your database. You will need access to a server with the Northwind SQL Server
sample database installed.
Try
' Specify a connection string. Replace the given value with a
' valid connection string for a Northwind SQL Server sample
' database accessible to your system.
Dim connectionString As String = _
"Integrated Security=SSPI;Persist Security Info=False;" + _
"Initial Catalog=Northwind;Data Source=localhost"
http://msdn2.microsoft.com/en-us/library/fbk67b6z(vs.80,d=printer).aspx 5/23/2007
How to: Bind Data to the Windows Forms DataGridView Control Page 2 of 6
Me.bindingSource1.DataSource = table
' Resize the DataGridView columns to fit the newly loaded content.
Me.dataGridView1.AutoResizeColumns( _
DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader)
Catch ex As SqlException
MessageBox.Show("To run this example, replace the value of the " + _
"connectionString variable with a connection string that is " + _
"valid for your system.")
End Try
End Sub
C# Copy Code
http://msdn2.microsoft.com/en-us/library/fbk67b6z(vs.80,d=printer).aspx 5/23/2007
How to: Bind Data to the Windows Forms DataGridView Control Page 3 of 6
End Sub
C# Copy Code
Example
The following complete code example provides buttons for reloading data from the database and
submitting changes to the database.
Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.Windows.Forms
<STAThreadAttribute()> _
Public Shared Sub Main()
Application.Run(New Form1())
End Sub
Me.dataGridView1.Dock = DockStyle.Fill
Me.reloadButton.Text = "reload"
Me.submitButton.Text = "submit"
End Sub
http://msdn2.microsoft.com/en-us/library/fbk67b6z(vs.80,d=printer).aspx 5/23/2007
How to: Bind Data to the Windows Forms DataGridView Control Page 4 of 6
Me.dataGridView1.DataSource = Me.bindingSource1
GetData("select * from Customers")
End Sub
End Sub
End Sub
Try
' Specify a connection string. Replace the given value with a
' valid connection string for a Northwind SQL Server sample
' database accessible to your system.
Dim connectionString As String = _
"Integrated Security=SSPI;Persist Security Info=False;" + _
"Initial Catalog=Northwind;Data Source=localhost"
' Resize the DataGridView columns to fit the newly loaded content.
Me.dataGridView1.AutoResizeColumns( _
DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader)
Catch ex As SqlException
MessageBox.Show("To run this example, replace the value of the " + _
"connectionString variable with a connection string that is " + _
"valid for your system.")
End Try
End Sub
End Class
C# Copy Code
using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
[STAThreadAttribute()]
public static void Main()
{
Application.Run(new Form1());
}
http://msdn2.microsoft.com/en-us/library/fbk67b6z(vs.80,d=printer).aspx 5/23/2007
How to: Bind Data to the Windows Forms DataGridView Control Page 5 of 6
public Form1()
{
dataGridView1.Dock = DockStyle.Fill;
reloadButton.Text = "reload";
submitButton.Text = "submit";
reloadButton.Click += new System.EventHandler(reloadButton_Click);
submitButton.Click += new System.EventHandler(submitButton_Click);
http://msdn2.microsoft.com/en-us/library/fbk67b6z(vs.80,d=printer).aspx 5/23/2007
How to: Bind Data to the Windows Forms DataGridView Control Page 6 of 6
For information about building this example from the command line for Visual Basic or Visual C#, see
Building from the Command Line (Visual Basic) [ http://msdn2.microsoft.com/en-us/library/25fz1td5
(VS.80).aspx ] or Command-Line Building [ http://msdn2.microsoft.com/en-us/library/78f4aasd
(VS.80).aspx ] . You can also build this example in Visual Studio by pasting the code into a new project.
For more information, see How to: Compile and Run a Complete Windows Forms Code Example Using
Visual Studio [ http://msdn2.microsoft.com/en-us/bb129228(vs.80).aspx ] and How to: Compile and
Run a Complete Windows Forms Code Example Using Visual Studio [ http://msdn2.microsoft.com/en-
us/bb129228(vs.90).aspx ] .
Security
Storing sensitive information, such as a password, within the connection string can affect the security of
your application. Using Windows Authentication (also known as integrated security) is a more secure way to
control access to a database. For more information, see Securing Connection Strings
[ http://msdn2.microsoft.com/en-us/library/89211k9b(VS.80).aspx ] .
See Also
Reference
DataGridView [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview
(VS.80).aspx ]
System.Windows.Forms.DataGridView.DataSource [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.datasource(VS.80).aspx ]
BindingSource [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.bindingsource
(VS.80).aspx ]
Concepts
Securing Connection Strings [ http://msdn2.microsoft.com/en-us/library/89211k9b(VS.80).aspx ]
Other Resources
Displaying Data in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/ms171600(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/fbk67b6z(vs.80,d=printer).aspx 5/23/2007
How to: Autogenerate Columns in a Data-Bound Windows Forms DataGridView Control Page 1 of 2
If the DataGridView control already has columns when you set the DataSource
[ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcomboboxcolumn.datasource(VS.80).aspx ] property, the
existing bound columns are compared to the columns in the data source and preserved whenever there is a
match. Unbound columns are always preserved. Bound columns for which there is no match in the data
source are removed. Columns in the data source for which there is no match in the control generate new
DataGridViewColumn objects, which are added to the end of the Columns
[ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview.columns(VS.80).aspx ]
collection.
Example
With customersDataGridView
.AutoGenerateColumns = True
.DataSource = customersDataSet
.DataMember = "Customers"
End With
End Sub
C# Copy Code
See Also
http://msdn2.microsoft.com/en-us/library/28bfhf10(vs.80,d=printer).aspx 5/23/2007
How to: Autogenerate Columns in a Data-Bound Windows Forms DataGridView Control Page 2 of 2
Tasks
How to: Remove Autogenerated Columns from a Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/hbtwc35f(VS.80).aspx ]
Reference
DataGridView [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview
(VS.80).aspx ]
System.Windows.Forms.DataGridView.AutoGenerateColumns [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.autogeneratecolumns(VS.80).aspx ]
Other Resources
Displaying Data in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/ms171600(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/28bfhf10(vs.80,d=printer).aspx 5/23/2007
How to: Remove Autogenerated Columns from a Windows Forms DataGridView Control Page 1 of 2
With dataGridView1
.AutoGenerateColumns = True
.DataSource = customersDataSet
.Columns.Remove("Fax")
End With
C# Copy Code
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = customersDataSet;
dataGridView1.Columns.Remove("Fax");
dataGridView1.Columns("CustomerID").Visible = False
C# Copy Code
dataGridView1.Columns["CustomerID"].Visible = false;
Example
With dataGridView1
.AutoGenerateColumns = True
.DataSource = customersDataSet
.Columns.Remove("Fax")
.Columns("CustomerID").Visible = False
End With
http://msdn2.microsoft.com/en-us/library/hbtwc35f(vs.80,d=printer).aspx 5/23/2007
How to: Remove Autogenerated Columns from a Windows Forms DataGridView Control Page 2 of 2
End Sub
C# Copy Code
z A DataGridView control named dataGridView1 bound to a table that contains Fax and
CustomerID columns, such as the Customers table in the Northwind sample database.
z References to the System [ http://msdn2.microsoft.com/en-us/library/system(VS.80).aspx ] and
System.Windows.Forms [ http://msdn2.microsoft.com/en-us/library/system.windows.forms
(VS.80).aspx ] assemblies.
See Also
Reference
DataGridView [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview
(VS.80).aspx ]
System.Windows.Forms.DataGridView.AutoGenerateColumns [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.autogeneratecolumns(VS.80).aspx ]
System.Windows.Forms.DataGridView.Columns [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.columns(VS.80).aspx ]
System.Windows.Forms.DataGridViewColumnCollection.Remove [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcolumncollection.remove(VS.80).aspx ]
System.Windows.Forms.DataGridViewColumn.Visible [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcolumn.visible(VS.80).aspx ]
Other Resources
Displaying Data in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/ms171600(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/hbtwc35f(vs.80,d=printer).aspx 5/23/2007
How to: Change the Order of Columns in the Windows Forms DataGridView Control Page 1 of 2
The following code example repositions some of the columns automatically generated when binding to the
Customers table in the Northwind sample database. For more information about how to bind the
DataGridView control to a database table, see How to: Bind Data to the Windows Forms DataGridView
Control [ http://msdn2.microsoft.com/en-us/library/fbk67b6z(VS.80).aspx ] .
There is support for this task in Visual Studio. For more information, see How to: Change the Order of
Columns in the Windows Forms DataGridView Control Using the Designer [ http://msdn2.microsoft.com/en-
us/hb1dk7ax(vs.80).aspx ] and How to: Change the Order of Columns in the Windows Forms DataGridView
Control Using the Designer [ http://msdn2.microsoft.com/en-us/hb1dk7ax(vs.90).aspx ] .
Example
With customersDataGridView
.Columns("CustomerID").Visible = False
.Columns("ContactName").DisplayIndex = 0
.Columns("ContactTitle").DisplayIndex = 1
.Columns("City").DisplayIndex = 2
.Columns("Country").DisplayIndex = 3
.Columns("CompanyName").DisplayIndex = 4
End With
End Sub
C# Copy Code
http://msdn2.microsoft.com/en-us/library/wkfe535h(vs.80,d=printer).aspx 5/23/2007
How to: Change the Order of Columns in the Windows Forms DataGridView Control Page 2 of 2
See Also
Tasks
How to: Bind Data to the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/fbk67b6z(VS.80).aspx ]
Reference
DataGridView [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview
(VS.80).aspx ]
DataGridViewColumn [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcolumn(VS.80).aspx ]
System.Windows.Forms.DataGridViewColumn.DisplayIndex [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcolumn.displayindex(VS.80).aspx ]
System.Windows.Forms.DataGridViewColumn.Visible [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcolumn.visible(VS.80).aspx ]
Other Resources
Displaying Data in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/ms171600(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/wkfe535h(vs.80,d=printer).aspx 5/23/2007
How to: Add an Unbound Column to a Data-Bound Windows Forms DataGridView Cont... Page 1 of 2
The following code example demonstrates how to create an unbound column of Details buttons to display a
child table related to a particular row in a parent table when you implement a master/detail scenario. To
respond to button clicks, implement a System.Windows.Forms.DataGridView.CellClick
[ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview.cellclick(VS.80).aspx ]
event handler that displays a form containing the child table.
There is support for this task in Visual Studio. For more information, see How to: Add and Remove Columns
in the Windows Forms DataGridView Control Using the Designer [ http://msdn2.microsoft.com/en-
us/dyyesckz(vs.80).aspx ] and How to: Add and Remove Columns in the Windows Forms DataGridView
Control Using the Designer [ http://msdn2.microsoft.com/en-us/dyyesckz(vs.90).aspx ] .
Example
With buttonColumn
.HeaderText = "Details"
.Name = "Details"
.Text = "View Details"
' Use the Text property for the button text for all cells rather
' than using each cell's value as the text for its own button.
.UseColumnTextForButtonValue = True
End With
End Sub
C# Copy Code
// Use the Text property for the button text for all cells rather
// than using each cell's value as the text for its own button.
buttonColumn.UseColumnTextForButtonValue = true;
http://msdn2.microsoft.com/en-us/library/zkatshfa(vs.80,d=printer).aspx 5/23/2007
How to: Add an Unbound Column to a Data-Bound Windows Forms DataGridView Cont... Page 2 of 2
See Also
Reference
DataGridView [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview
(VS.80).aspx ]
Concepts
Data Display Modes in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/cd28yf6d(VS.80).aspx ]
Other Resources
Displaying Data in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/ms171600(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/zkatshfa(vs.80,d=printer).aspx 5/23/2007
How to: Bind Objects to Windows Forms DataGridView Controls Page 1 of 4
Example
Imports System.Windows.Forms
Imports System.Collections.Generic
dataGridView1.Columns.Add(CreateComboBoxWithEnums())
http://msdn2.microsoft.com/en-us/library/y0wfd4yz(vs.80,d=printer).aspx 5/23/2007
How to: Bind Objects to Windows Forms DataGridView Controls Page 2 of 4
Me.AutoSize = True
Me.Text = "DataGridView object binding demo"
End Sub
hisTitle = title
hisName = name
Me.good = good
End Sub
End Class
C# Copy Code
using System;
using System.Windows.Forms;
public EnumsAndComboBox()
{
http://msdn2.microsoft.com/en-us/library/y0wfd4yz(vs.80,d=printer).aspx 5/23/2007
How to: Bind Objects to Windows Forms DataGridView Controls Page 3 of 4
dataGridView1.Columns.Add(CreateComboBoxWithEnums());
DataGridViewComboBoxColumn CreateComboBoxWithEnums()
{
DataGridViewComboBoxColumn combo = new DataGridViewComboBoxColumn();
combo.DataSource = Enum.GetValues(typeof(Title));
combo.DataPropertyName = "Title";
combo.Name = "Title";
return combo;
}
#region "business object"
private class Knight
{
private string hisName;
private bool good;
private Title hisTitle;
public Knight()
{
hisTitle = Title.Sir;
hisName = "<enter name>";
good = true;
}
set
{
hisName = value;
}
}
http://msdn2.microsoft.com/en-us/library/y0wfd4yz(vs.80,d=printer).aspx 5/23/2007
How to: Bind Objects to Windows Forms DataGridView Controls Page 4 of 4
get
{
return good;
}
set
{
good = value;
}
}
[STAThread]
public static void Main()
{
Application.Run(new EnumsAndComboBox());
}
For information about building this example from the command line for Visual Basic or Visual C#, see
Building from the Command Line (Visual Basic) [ http://msdn2.microsoft.com/en-us/library/25fz1td5
(VS.80).aspx ] or Command-Line Building [ http://msdn2.microsoft.com/en-us/library/78f4aasd
(VS.80).aspx ] . You can also build this example in Visual Studio by pasting the code into a new project.
For more information, see How to: Compile and Run a Complete Windows Forms Code Example Using
Visual Studio [ http://msdn2.microsoft.com/en-us/bb129228(vs.80).aspx ] and How to: Compile and
Run a Complete Windows Forms Code Example Using Visual Studio [ http://msdn2.microsoft.com/en-
us/bb129228(vs.90).aspx ] .
See Also
Tasks
How to: Access Objects Bound to Windows Forms DataGridView Rows [ http://msdn2.microsoft.com/en-
us/library/4wszzzc7(VS.80).aspx ]
Reference
DataGridView [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview
(VS.80).aspx ]
Other Resources
Displaying Data in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/ms171600(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/y0wfd4yz(vs.80,d=printer).aspx 5/23/2007
How to: Access Objects Bound to Windows Forms DataGridView Rows Page 1 of 4
If these objects contain additional information and code that you want to access, you can reach it through
row objects. In the following code example, users can select multiple rows and click a button to send an
invoice to each of the corresponding customers.
Next
End Sub
C# Copy Code
Example
The complete code example includes a simple Customer implementation and binds the DataGridView
to an ArrayList [ http://msdn2.microsoft.com/en-us/library/system.collections.arraylist(VS.80).aspx ]
containing a few Customer objects. The Click [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.control.click(VS.80).aspx ] event handler of the
System.Windows.Forms.Button [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.button(VS.80).aspx ] must access the Customer objects through the
rows, because the customer collection is not accessible outside the System.Windows.Forms.Form.Load
[ http://msdn2.microsoft.com/en-us/library/system.windows.forms.form.load(VS.80).aspx ] event
handler.
http://msdn2.microsoft.com/en-us/library/4wszzzc7(vs.80,d=printer).aspx 5/23/2007
How to: Access Objects Bound to Windows Forms DataGridView Rows Page 2 of 4
Imports System
Imports System.Windows.Forms
Application.Run(New DataGridViewObjectBinding())
End Sub
Me.DataGridView1.Dock = DockStyle.Fill
Me.Controls.Add(Me.DataGridView1)
End Sub
End Sub
Next
End Sub
End Class
http://msdn2.microsoft.com/en-us/library/4wszzzc7(vs.80,d=printer).aspx 5/23/2007
How to: Access Objects Bound to Windows Forms DataGridView Rows Page 3 of 4
Return nameValue
End Get
Set(ByVal value As String)
nameValue = value
End Set
End Property
End Class
C# Copy Code
using System;
using System.Windows.Forms;
http://msdn2.microsoft.com/en-us/library/4wszzzc7(vs.80,d=printer).aspx 5/23/2007
How to: Access Objects Bound to Windows Forms DataGridView Rows Page 4 of 4
For information about building this example from the command line for Visual Basic or Visual C#, see
Building from the Command Line (Visual Basic) [ http://msdn2.microsoft.com/en-us/library/25fz1td5
(VS.80).aspx ] or Command-Line Building [ http://msdn2.microsoft.com/en-us/library/78f4aasd
(VS.80).aspx ] . You can also build this example in Visual Studio by pasting the code into a new project.
For more information, see How to: Compile and Run a Complete Windows Forms Code Example Using
Visual Studio [ http://msdn2.microsoft.com/en-us/bb129228(vs.80).aspx ] and How to: Compile and
Run a Complete Windows Forms Code Example Using Visual Studio [ http://msdn2.microsoft.com/en-
us/bb129228(vs.90).aspx ] .
See Also
Tasks
How to: Bind Objects to Windows Forms DataGridView Controls [ http://msdn2.microsoft.com/en-
us/library/y0wfd4yz(VS.80).aspx ]
Reference
DataGridView [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview
(VS.80).aspx ]
DataGridViewRow [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridviewrow
(VS.80).aspx ]
System.Windows.Forms.DataGridViewRow.DataBoundItem [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewrow.databounditem(VS.80).aspx ]
Other Resources
Displaying Data in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/ms171600(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/4wszzzc7(vs.80,d=printer).aspx 5/23/2007
How to: Access Objects in a Windows Forms DataGridViewComboBoxCell Drop-Down ... Page 1 of 8
To retrieve the business object through the cell value, the ValueMember property must indicate a property
that returns a reference to the business object itself. Therefore, if the type of the business object is not
under your control, you must add such a property by extending the type through inheritance.
The following procedures demonstrate how to populate a drop-down list with business objects and retrieve
the objects through the cell Value property.
' Populate the combo box drop-down list with Employee objects.
For Each e As Employee In employees
assignedToColumn.Items.Add(e)
Next
C# Copy Code
DataGridViewComboBoxColumn assignedToColumn =
http://msdn2.microsoft.com/en-us/library/ms404353(vs.80,d=printer).aspx 5/23/2007
How to: Access Objects in a Windows Forms DataGridViewComboBoxCell Drop-Down ... Page 2 of 8
new DataGridViewComboBoxColumn();
assignedToColumn.DisplayMember = "Name"
assignedToColumn.ValueMember = "Self"
C# Copy Code
assignedToColumn.DisplayMember = "Name";
assignedToColumn.ValueMember = "Self";
3. Make sure that your business object type contains a property that returns a reference to the current
instance. This property must be named with the value assigned to ValueMember in the previous
step.
C# Copy Code
z Get the cell Value property and cast it to the business object type.
' Retrieve the Employee object from the "Assigned To" cell.
Dim assignedTo As Employee = TryCast(dataGridView1.Rows(e.RowIndex) _
.Cells("Assigned To").Value, Employee)
C# Copy Code
http://msdn2.microsoft.com/en-us/library/ms404353(vs.80,d=printer).aspx 5/23/2007
How to: Access Objects in a Windows Forms DataGridViewComboBoxCell Drop-Down ... Page 3 of 8
Example
The complete example demonstrates the use of business objects in a drop-down list. In the example, a
DataGridView control is bound to a collection of Task objects. Each Task object has an AssignedTo
property that indicates the Employee object currently assigned to that task. The Assigned To column
displays the Name property value for each assigned employee, or "unassigned" if the Task.AssignedTo
property value is null.
1. Change assignments in the Assigned To column by selecting different values from the drop-
down lists or pressing CTRL+0 in a combo-box cell.
2. Click Generate Report to display the current assignments. This demonstrates that a change in
the Assigned To column automatically updates the tasks collection.
3. Click a Request Status button to call the RequestStatus method of the current Employee
object for that row. This demonstrates that the selected object has been successfully retrieved.
Imports System
Imports System.Text
Imports System.Collections.Generic
Imports System.Windows.Forms
<STAThread()> _
Public Sub Main()
Application.Run(New Form1)
End Sub
Sub New()
dataGridView1.Dock = DockStyle.Fill
dataGridView1.AutoSizeColumnsMode = _
DataGridViewAutoSizeColumnsMode.AllCells
reportButton.Text = "Generate Report"
reportButton.Dock = DockStyle.Top
Controls.Add(dataGridView1)
Controls.Add(reportButton)
Text = "DataGridViewComboBoxColumn Demo"
End Sub
' Initializes the data source and populates the DataGridView control.
Private Sub Form1_Load(ByVal sender As Object, _
ByVal e As EventArgs) Handles Me.Load
PopulateLists()
dataGridView1.AutoGenerateColumns = False
dataGridView1.DataSource = tasks
AddColumns()
End Sub
http://msdn2.microsoft.com/en-us/library/ms404353(vs.80,d=printer).aspx 5/23/2007
How to: Access Objects in a Windows Forms DataGridViewComboBoxCell Drop-Down ... Page 4 of 8
' Populate the combo box drop-down list with Employee objects.
For Each e As Employee In employees
assignedToColumn.Items.Add(e)
Next
dataGridView1.Columns.Add(idColumn)
dataGridView1.Columns.Add(assignedToColumn)
dataGridView1.Columns.Add(buttonColumn)
End Sub
End Sub
' Retrieve the Employee object from the "Assigned To" cell.
Dim assignedTo As Employee = TryCast(dataGridView1.Rows(e.RowIndex) _
.Cells("Assigned To").Value, Employee)
http://msdn2.microsoft.com/en-us/library/ms404353(vs.80,d=printer).aspx 5/23/2007
How to: Access Objects in a Windows Forms DataGridViewComboBoxCell Drop-Down ... Page 5 of 8
End Sub
End Class
End Class
End Class
C# Copy Code
using System;
using System.Text;
using System.Collections.Generic;
using System.Windows.Forms;
http://msdn2.microsoft.com/en-us/library/ms404353(vs.80,d=printer).aspx 5/23/2007
How to: Access Objects in a Windows Forms DataGridViewComboBoxCell Drop-Down ... Page 6 of 8
[STAThread]
public static void Main()
{
Application.Run(new Form1());
}
public Form1()
{
dataGridView1.Dock = DockStyle.Fill;
dataGridView1.AutoSizeColumnsMode =
DataGridViewAutoSizeColumnsMode.AllCells;
reportButton.Text = "Generate Report";
reportButton.Dock = DockStyle.Top;
reportButton.Click += new EventHandler(reportButton_Click);
Controls.Add(dataGridView1);
Controls.Add(reportButton);
Load += new EventHandler(Form1_Load);
Text = "DataGridViewComboBoxColumn Demo";
}
DataGridViewComboBoxColumn assignedToColumn =
new DataGridViewComboBoxColumn();
dataGridView1.Columns.Add(idColumn);
dataGridView1.Columns.Add(assignedToColumn);
dataGridView1.Columns.Add(buttonColumn);
http://msdn2.microsoft.com/en-us/library/ms404353(vs.80,d=printer).aspx 5/23/2007
How to: Access Objects in a Windows Forms DataGridViewComboBoxCell Drop-Down ... Page 7 of 8
http://msdn2.microsoft.com/en-us/library/ms404353(vs.80,d=printer).aspx 5/23/2007
How to: Access Objects in a Windows Forms DataGridViewComboBoxCell Drop-Down ... Page 8 of 8
nameValue = name;
}
See Also
Reference
DataGridView [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview
(VS.80).aspx ]
DataGridViewComboBoxColumn [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcomboboxcolumn(VS.80).aspx ]
System.Windows.Forms.DataGridViewComboBoxColumn.Items [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcomboboxcolumn.items(VS.80).aspx ]
System.Windows.Forms.DataGridViewComboBoxColumn.DataSource [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcomboboxcolumn.datasource(VS.80).aspx ]
System.Windows.Forms.DataGridViewComboBoxColumn.ValueMember [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcomboboxcolumn.valuemember(VS.80).aspx ]
DataGridViewComboBoxCell [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcomboboxcell(VS.80).aspx ]
System.Windows.Forms.DataGridViewComboBoxCell.Items [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcomboboxcell.items(VS.80).aspx ]
System.Windows.Forms.DataGridViewComboBoxCell.DataSource [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcomboboxcell.datasource(VS.80).aspx ]
System.Windows.Forms.DataGridViewComboBoxCell.ValueMember [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcomboboxcell.valuemember(VS.80).aspx ]
System.Windows.Forms.DataGridViewCell.Value [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcell.value(VS.80).aspx ]
ComboBox [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.combobox(VS.80).aspx ]
Other Resources
Displaying Data in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/ms171600(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/ms404353(vs.80,d=printer).aspx 5/23/2007
Walkthrough: Creating a Master/Detail Form Using Two Windows Forms DataGridView ... Page 1 of 6
Implementing a master/detail form is easy using the interaction between the DataGridView control and
the BindingSource [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.bindingsource
(VS.80).aspx ] component. In this walkthrough, you will build the form using two DataGridView controls
and two BindingSource components. The form will show two related tables in the Northwind SQL Server
sample database: Customers and Orders. When you are finished, you will have a form that shows all the
customers in the database in the master DataGridView and all the orders for the selected customer in the
detail DataGridView.
To copy the code in this topic as a single listing, see How to: Create a Master/Detail Form Using Two
Windows Forms DataGridView Controls [ http://msdn2.microsoft.com/en-us/library/c12c1kx4
(VS.80).aspx ] .
Prerequisites
In order to complete this walkthrough, you will need:
z Access to a server that has the Northwind SQL Server sample database.
Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.Windows.Forms
<STAThreadAttribute()> _
Public Shared Sub Main()
Application.Run(New Form1())
End Sub
http://msdn2.microsoft.com/en-us/library/y8c0cxey(vs.80,d=printer).aspx 5/23/2007
Walkthrough: Creating a Master/Detail Form Using Two Windows Forms DataGridView ... Page 2 of 6
masterDataGridView.Dock = DockStyle.Fill
detailsDataGridView.Dock = DockStyle.Fill
Me.Controls.Add(splitContainer1)
Me.Text = "DataGridView master/detail demo"
End Sub
<br /><span space="preserve">...</span><br />End Class
C# Copy Code
using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
[STAThreadAttribute()]
public static void Main()
{
Application.Run(new Form1());
}
this.Controls.Add(splitContainer1);
this.Load += new System.EventHandler(Form1_Load);
this.Text = "DataGridView master/detail demo";
}
<br /><span space="preserve">...</span><br />}
2. Implement a method in your form's class definition for handling the detail of connecting to the
http://msdn2.microsoft.com/en-us/library/y8c0cxey(vs.80,d=printer).aspx 5/23/2007
Walkthrough: Creating a Master/Detail Form Using Two Windows Forms DataGridView ... Page 3 of 6
Security Note
Storing sensitive information, such as a password, within the connection string can affect
the security of your application. Using Windows Authentication (also known as integrated
security) is a more secure way to control access to a database. For more information, see
Securing Connection Strings [ http://msdn2.microsoft.com/en-us/library/89211k9b
(VS.80).aspx ] .
Try
' Specify a connection string. Replace the given value with a
' valid connection string for a Northwind SQL Server sample
' database accessible to your system.
Dim connectionString As String = _
"Integrated Security=SSPI;Persist Security Info=False;" & _
"Initial Catalog=Northwind;Data Source=localhost"
Dim connection As New SqlConnection(connectionString)
' Bind the details data connector to the master data connector,
' using the DataRelation name to filter the information in the
' details table based on the current row in the master table.
detailsBindingSource.DataSource = masterBindingSource
detailsBindingSource.DataMember = "CustomersOrders"
Catch ex As SqlException
http://msdn2.microsoft.com/en-us/library/y8c0cxey(vs.80,d=printer).aspx 5/23/2007
Walkthrough: Creating a Master/Detail Form Using Two Windows Forms DataGridView ... Page 4 of 6
MessageBox.Show("To run this example, replace the value of the " & _
"connectionString variable with a connection string that is " & _
"valid for your system.")
End Try
End Sub
C# Copy Code
// Create a DataSet.
DataSet data = new DataSet();
data.Locale = System.Globalization.CultureInfo.InvariantCulture;
http://msdn2.microsoft.com/en-us/library/y8c0cxey(vs.80,d=printer).aspx 5/23/2007
Walkthrough: Creating a Master/Detail Form Using Two Windows Forms DataGridView ... Page 5 of 6
' Resize the master DataGridView columns to fit the newly loaded data.
masterDataGridView.AutoResizeColumns()
End Sub
C# Copy Code
// Resize the master DataGridView columns to fit the newly loaded data.
masterDataGridView.AutoResizeColumns();
You will see two DataGridView controls, one above the other. On top are the customers from the
Northwind Customers table, and at the bottom are the Orders corresponding to the selected
customer. As you select different rows in the upper DataGridView, the contents of the lower
DataGridView change accordingly.
http://msdn2.microsoft.com/en-us/library/y8c0cxey(vs.80,d=printer).aspx 5/23/2007
Walkthrough: Creating a Master/Detail Form Using Two Windows Forms DataGridView ... Page 6 of 6
Next Steps
This application gives you a basic understanding of the DataGridView control's capabilities. You can
customize the appearance and behavior of the DataGridView control in several ways:
z Change border and header styles. For more information, see How to: Change the Border and
Gridline Styles in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/ehz9ksfa(VS.80).aspx ] .
z Enable or restrict user input to the DataGridView control. For more information, see How to:
Prevent Row Addition and Deletion in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/61bk13ye(VS.80).aspx ] , and How to: Make Columns
Read-Only in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/cze614bb(VS.80).aspx ] .
z Validate user input to the DataGridView control. For more information, see Walkthrough:
Validating Data in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/ykdxa0bc(VS.80).aspx ] .
z Handle very large data sets using virtual mode. For more information, see Walkthrough:
Implementing Virtual Mode in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/15a31akc(VS.80).aspx ] .
z Customize the appearance of cells. For more information, see How to: Customize the Appearance
of Cells in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/hta8z9sz(VS.80).aspx ] and How to: Set Default Cell Styles for the Windows Forms
DataGridView Control [ http://msdn2.microsoft.com/en-us/library/k4sab6f9(VS.80).aspx ] .
See Also
Tasks
How to: Create a Master/Detail Form Using Two Windows Forms DataGridView Controls
[ http://msdn2.microsoft.com/en-us/library/c12c1kx4(VS.80).aspx ]
Reference
DataGridView [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview
(VS.80).aspx ]
BindingSource [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.bindingsource
(VS.80).aspx ]
Concepts
Securing Connection Strings [ http://msdn2.microsoft.com/en-us/library/89211k9b(VS.80).aspx ]
Other Resources
Displaying Data in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/ms171600(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/y8c0cxey(vs.80,d=printer).aspx 5/23/2007
How to: Create a Master/Detail Form Using Two Windows Forms DataGridView Controls Page 1 of 4
One BindingSource is bound to the parent Customers table in the data set. This data is displayed in the
master DataGridView control. The other BindingSource is bound to the first data connector. The
DataMember [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.bindingsource.datamember(VS.80).aspx ] property of the second
BindingSource is set to the DataRelation [ http://msdn2.microsoft.com/en-
us/library/system.data.datarelation(VS.80).aspx ] name. This causes the associated detail DataGridView
control to display the rows of the child Orders table that correspond to the current row in the master
DataGridView control.
For a complete explanation of this code example, see Walkthrough: Creating a Master/Detail Form Using
Two Windows Forms DataGridView Controls [ http://msdn2.microsoft.com/en-us/library/y8c0cxey
(VS.80).aspx ] .
Example
Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.Windows.Forms
<STAThreadAttribute()> _
Public Shared Sub Main()
Application.Run(New Form1())
End Sub
masterDataGridView.Dock = DockStyle.Fill
detailsDataGridView.Dock = DockStyle.Fill
Me.Controls.Add(splitContainer1)
Me.Text = "DataGridView master/detail demo"
End Sub
http://msdn2.microsoft.com/en-us/library/c12c1kx4(vs.80,d=printer).aspx 5/23/2007
How to: Create a Master/Detail Form Using Two Windows Forms DataGridView Controls Page 2 of 4
Handles Me.Load
' Resize the master DataGridView columns to fit the newly loaded data.
masterDataGridView.AutoResizeColumns()
End Sub
Try
' Specify a connection string. Replace the given value with a
' valid connection string for a Northwind SQL Server sample
' database accessible to your system.
Dim connectionString As String = _
"Integrated Security=SSPI;Persist Security Info=False;" & _
"Initial Catalog=Northwind;Data Source=localhost"
Dim connection As New SqlConnection(connectionString)
' Bind the details data connector to the master data connector,
' using the DataRelation name to filter the information in the
' details table based on the current row in the master table.
detailsBindingSource.DataSource = masterBindingSource
detailsBindingSource.DataMember = "CustomersOrders"
Catch ex As SqlException
MessageBox.Show("To run this example, replace the value of the " & _
"connectionString variable with a connection string that is " & _
"valid for your system.")
End Try
End Sub
End Class
C# Copy Code
using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
http://msdn2.microsoft.com/en-us/library/c12c1kx4(vs.80,d=printer).aspx 5/23/2007
How to: Create a Master/Detail Form Using Two Windows Forms DataGridView Controls Page 3 of 4
[STAThreadAttribute()]
public static void Main()
{
Application.Run(new Form1());
}
this.Controls.Add(splitContainer1);
this.Load += new System.EventHandler(Form1_Load);
this.Text = "DataGridView master/detail demo";
}
// Resize the master DataGridView columns to fit the newly loaded data.
masterDataGridView.AutoResizeColumns();
// Create a DataSet.
DataSet data = new DataSet();
data.Locale = System.Globalization.CultureInfo.InvariantCulture;
http://msdn2.microsoft.com/en-us/library/c12c1kx4(vs.80,d=printer).aspx 5/23/2007
How to: Create a Master/Detail Form Using Two Windows Forms DataGridView Controls Page 4 of 4
detailsBindingSource.DataSource = masterBindingSource;
detailsBindingSource.DataMember = "CustomersOrders";
}
catch (SqlException)
{
MessageBox.Show("To run this example, replace the value of the " +
"connectionString variable with a connection string that is " +
"valid for your system.");
}
}
}
For information about building this example from the command line for Visual Basic or Visual C#, see
Building from the Command Line (Visual Basic) [ http://msdn2.microsoft.com/en-us/library/25fz1td5
(VS.80).aspx ] or Command-Line Building [ http://msdn2.microsoft.com/en-us/library/78f4aasd
(VS.80).aspx ] . You can also build this example in Visual Studio by pasting the code into a new project.
For more information, see How to: Compile and Run a Complete Windows Forms Code Example Using
Visual Studio [ http://msdn2.microsoft.com/en-us/bb129228(vs.80).aspx ] and How to: Compile and
Run a Complete Windows Forms Code Example Using Visual Studio [ http://msdn2.microsoft.com/en-
us/bb129228(vs.90).aspx ] .
Security
Storing sensitive information, such as a password, within the connection string can affect the security of
your application. Using Windows Authentication (also known as integrated security) is a more secure way to
control access to a database. For more information, see Securing Connection Strings
[ http://msdn2.microsoft.com/en-us/library/89211k9b(VS.80).aspx ] .
See Also
Tasks
Walkthrough: Creating a Master/Detail Form Using Two Windows Forms DataGridView Controls
[ http://msdn2.microsoft.com/en-us/library/y8c0cxey(VS.80).aspx ]
Reference
DataGridView [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview
(VS.80).aspx ]
BindingSource [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.bindingsource
(VS.80).aspx ]
Concepts
Securing Connection Strings [ http://msdn2.microsoft.com/en-us/library/89211k9b(VS.80).aspx ]
Other Resources
Displaying Data in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/ms171600(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/c12c1kx4(vs.80,d=printer).aspx 5/23/2007
How to: Customize Data Formatting in the Windows Forms DataGridView Control Page 1 of 4
Cells in the Balance column that contain negative numbers are given a red background. You can also
format these cells as currency to display parentheses around negative values. For more information, see
How to: Format Data in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/f9x2790s(VS.80).aspx ] .
Cells in the Priority column display images in place of corresponding textual cell values. The Value
[ http://msdn2.microsoft.com/en-us/library/system.windows.forms.converteventargs.value(VS.80).aspx ]
property of the DataGridViewCellFormattingEventArgs [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcellformattingeventargs(VS.80).aspx ] is used both to get
the textual cell value and to set the corresponding image display value.
Example
Imports System
Imports System.Drawing
Imports System.Windows.Forms
Me.Controls.Add(dataGridView1)
End Sub
' Changes how cells are displayed depending on their columns and values.
http://msdn2.microsoft.com/en-us/library/z1cc356h(vs.80,d=printer).aspx 5/23/2007
How to: Customize Data Formatting in the Windows Forms DataGridView Control Page 2 of 4
' Set the background to red for negative values in the Balance column.
If dataGridView1.Columns(e.ColumnIndex).Name.Equals("Balance") Then
e.CellStyle.BackColor = Color.Red
e.CellStyle.SelectionBackColor = Color.DarkRed
End If
End If
Case "high"
e.Value = highPriImage
Case "medium"
e.Value = mediumPriImage
Case "low"
e.Value = lowPriImage
End Select
End If
End Sub
End Class
C# Copy Code
using System;
using System.Drawing;
using System.Windows.Forms;
public Form1()
{
// Initialize the images.
try
{
highPriImage = new Bitmap("highPri.bmp");
mediumPriImage = new Bitmap("mediumPri.bmp");
lowPriImage = new Bitmap("lowPri.bmp");
}
catch (ArgumentException)
{
MessageBox.Show("The Priority column requires Bitmap images " +
"named highPri.bmp, mediumPri.bmp, and lowPri.bmp " +
"residing in the same directory as the executable file.");
}
http://msdn2.microsoft.com/en-us/library/z1cc356h(vs.80,d=printer).aspx 5/23/2007
How to: Customize Data Formatting in the Windows Forms DataGridView Control Page 3 of 4
// Changes how cells are displayed depending on their columns and values.
private void dataGridView1_CellFormatting(object sender,
System.Windows.Forms.DataGridViewCellFormattingEventArgs e)
{
// Set the background to red for negative values in the Balance column.
if (dataGridView1.Columns[e.ColumnIndex].Name.Equals("Balance"))
{
Int32 intValue;
if (Int32.TryParse((String)e.Value, out intValue) &&
(intValue < 0))
{
e.CellStyle.BackColor = Color.Red;
e.CellStyle.SelectionBackColor = Color.DarkRed;
}
}
http://msdn2.microsoft.com/en-us/library/z1cc356h(vs.80,d=printer).aspx 5/23/2007
How to: Customize Data Formatting in the Windows Forms DataGridView Control Page 4 of 4
See Also
Tasks
How to: Format Data in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/f9x2790s(VS.80).aspx ]
Reference
System.Windows.Forms.DataGridView.DefaultCellStyle [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.defaultcellstyle(VS.80).aspx ]
System.Windows.Forms.DataGridViewBand.DefaultCellStyle [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewband.defaultcellstyle(VS.80).aspx ]
DataGridView [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview
(VS.80).aspx ]
DataGridViewCellStyle [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcellstyle(VS.80).aspx ]
Bitmap [ http://msdn2.microsoft.com/en-us/library/system.drawing.bitmap(VS.80).aspx ]
Concepts
Cell Styles in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/1yef90x0(VS.80).aspx ]
Data Formatting in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/hezscd0d(VS.80).aspx ]
Other Resources
Displaying Data in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/ms171600(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/z1cc356h(vs.80,d=printer).aspx 5/23/2007
Resizing Columns and Rows in the Windows Forms DataGridView Control Page 1 of 2
By default, users can drag row, column, and header dividers with the mouse to show more information.
Users can also double-click a divider to automatically resize the associated row, column, or header band
based on its contents.
The DataGridView control provides properties, methods, and events that enable you to customize or
disable all of these user-directed behaviors. Additionally, you can programmatically resize rows, columns,
and headers to fit their contents, or you can configure them to automatically resize themselves whenever
their contents change. You can also configure columns to automatically divide the available width of the
control in proportions that you specify.
In This Section
How to: Set the Sizing Modes of the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/fd004dhd(VS.80).aspx ]
Describes how to configure the sizing modes for common purposes.
How to: Programmatically Resize Cells to Fit Content in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/ff173xd4(VS.80).aspx ]
Provides demonstration code that you can use to experiment with programmatic resizing.
How to: Automatically Resize Cells When Content Changes in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/f71f07b5(VS.80).aspx ]
Provides demonstration code that you can use to experiment with automatic sizing modes.
Reference
DataGridView [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview
(VS.80).aspx ]
Provides reference documentation for the DataGridView control.
See Also
Other Resources
DataGridView Control (Windows Forms) [ http://msdn2.microsoft.com/en-us/library/e0ywh3cz
(VS.80).aspx ]
http://msdn2.microsoft.com/en-us/library/ms171604(vs.80,d=printer).aspx 5/23/2007
Resizing Columns and Rows in the Windows Forms DataGridView Control Page 2 of 2
Community Content
http://msdn2.microsoft.com/en-us/library/ms171604(vs.80,d=printer).aspx 5/23/2007
Sizing Options in the Windows Forms DataGridView Control Page 1 of 6
Occurrence Description
User resize Users can make size adjustments by dragging or double-clicking row, column, or
header dividers.
Control resize In column fill mode, column widths change when the control width changes; for
example, when the control is docked to its parent form and the user resizes the
form.
Cell value In content-based automatic sizing modes, sizes change to fit new display values.
change
Method call Programmatic content-based resizing lets you make opportunistic size adjustments
based on cell values at the time of the method call.
Property You can also set specific height and width values.
setting
By default, user resizing is enabled, automatic sizing is disabled, and cell values that are wider than their
columns are clipped.
The following table shows scenarios that you can use to adjust the default behavior or to use specific sizing
options to achieve particular effects.
Scenario Implementation
Use column fill Set the AutoSizeColumnsMode property to Fill. Initialize relative column widths
mode with by setting the column FillWeight [ http://msdn2.microsoft.com/en-
display values us/library/system.windows.forms.datagridviewcolumn.fillweight(VS.80).aspx ]
of varying properties or by calling the control AutoResizeColumns
sizes. [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.autoresizecolumns(VS.80).aspx ]
method after filling the control with data.
http://msdn2.microsoft.com/en-us/library/74b2wakt(vs.80,d=printer).aspx 5/23/2007
Sizing Options in the Windows Forms DataGridView Control Page 2 of 6
Use column fill Set the AutoSizeColumnsMode property to Fill. Set large MinimumWidth
mode with [ http://msdn2.microsoft.com/en-
values of us/library/system.windows.forms.datagridviewcolumn.minimumwidth
varying (VS.80).aspx ] values for columns that must always display some of their data or
importance. use a sizing option other than fill mode for specific columns.
Adjust sizes Set an automatic sizing property to a value that represents a content-based sizing
automatically mode. To avoid a performance penalty when working with large amounts of data,
whenever cell use a sizing mode that calculates displayed rows only.
contents
change to avoid
clipping and to
optimize the
use of space.
Adjust sizes to Use the appropriate sizing-mode enumeration values with automatic or
fit values in programmatic resizing. To adjust sizes to fit values in newly displayed rows while
displayed rows scrolling, call a resizing method in a Scroll [ http://msdn2.microsoft.com/en-
to avoid us/library/system.windows.forms.datagridview.scroll(VS.80).aspx ] event handler.
performance To customize user double-click resizing so that only values in displayed rows
penalties when determine the new sizes, call a resizing method in a RowDividerDoubleClick
working with [ http://msdn2.microsoft.com/en-
many rows. us/library/system.windows.forms.datagridview.rowdividerdoubleclick
(VS.80).aspx ] or ColumnDividerDoubleClick [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.columndividerdoubleclick
(VS.80).aspx ] event handler.
Adjust sizes to Call a content-based resizing method in an event handler. For example, use the
fit cell contents DataBindingComplete [ http://msdn2.microsoft.com/en-
only at specific us/library/system.windows.forms.datagridview.databindingcomplete(VS.80).aspx ]
times to avoid event to initialize sizes after binding, and handle the CellValidated
performance [ http://msdn2.microsoft.com/en-
penalties or to us/library/system.windows.forms.datagridview.cellvalidated(VS.80).aspx ] or
enable user CellValueChanged [ http://msdn2.microsoft.com/en-
resizing. us/library/system.windows.forms.datagridview.cellvaluechanged(VS.80).aspx ]
event to adjust sizes to compensate for user edits or changes in a bound data
source.
Adjust row Ensure that column widths are appropriate for displaying paragraphs of text and
heights for use automatic or programmatic content-based row sizing to adjust the heights.
multiline cell Also ensure that cells with multiline content are displayed using a WrapMode
http://msdn2.microsoft.com/en-us/library/74b2wakt(vs.80,d=printer).aspx 5/23/2007
Sizing Options in the Windows Forms DataGridView Control Page 3 of 6
contents. [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcellstyle.wrapmode(VS.80).aspx ]
cell style value of True [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewtristate(VS.80).aspx ] .
Typically, you will use an automatic column sizing mode to maintain column widths
or set them to specific widths before row heights are adjusted.
By default, users can resize rows, columns, and headers that do not use an automatic sizing mode based
on cell values. To prevent users from resizing with other modes, such as column fill mode, set one or more
of the following DataGridView properties:
z AllowUserToResizeColumns [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.allowusertoresizecolumns(VS.80).aspx ]
z AllowUserToResizeRows [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.allowusertoresizerows(VS.80).aspx ]
z ColumnHeadersHeightSizeMode [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.columnheadersheightsizemode(VS.80).aspx ]
z RowHeadersWidthSizeMode [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.rowheaderswidthsizemode(VS.80).aspx ]
You can also prevent users from resizing individual rows or columns by setting their Resizable
[ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridviewband.resizable
(VS.80).aspx ] properties. By default, the Resizable property value is based on the
AllowUserToResizeColumns property value for columns and the AllowUserToResizeRows property
value for rows. If you explicitly set Resizable to True or False, however, the specified value overrides the
control value is for that row or column. Set Resizable to NotSet [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewtristate(VS.80).aspx ] to restore the inheritance.
Because NotSet restores the value inheritance, the Resizable property will never return a NotSet value
unless the row or column has not been added to a DataGridView control. If you need to determine
whether the Resizable property value of a row or column is inherited, examine its State
[ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridviewelement.state
(VS.80).aspx ] property. If the State value includes the ResizableSet [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewelementstates(VS.80).aspx ] flag, the Resizable property
value is not inherited.
Automatic Sizing
There are two kinds of automatic sizing in the DataGridView control: column fill mode and content-based
automatic sizing.
Column fill mode causes the visible columns in the control to fill the width of the control's display area. For
more information about this mode, see Column Fill Mode in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/ms171605(VS.80).aspx ] .
You can also configure rows, columns, and headers to automatically adjust their sizes to fit their cell
contents. In this case, size adjustment occurs whenever cell contents change.
Note
If you maintain cell values in a custom data cache using virtual mode, automatic sizing occurs when
the user edits a cell value but does not occur when you alter a cached value outside of a
CellValuePushed [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.cellvaluepushed(VS.80).aspx ] event handler. In this
case, call the UpdateCellValue [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.updatecellvalue(VS.80).aspx ] method to force the
control to update the cell display and apply the current automatic sizing modes.
If content-based automatic sizing is enabled for one dimension only—that is, for rows but not columns, or
for columns but not rows—and WrapMode is also enabled, size adjustment also occurs whenever the other
http://msdn2.microsoft.com/en-us/library/74b2wakt(vs.80,d=printer).aspx 5/23/2007
Sizing Options in the Windows Forms DataGridView Control Page 4 of 6
dimension changes. For example, if rows but not columns are configured for automatic sizing and
WrapMode is enabled, users can drag column dividers to change the width of a column and row heights
will automatically adjust so that cell contents are still fully displayed.
If you configure both rows and columns for content-based automatic sizing and WrapMode is enabled, the
DataGridView control will adjust sizes whenever cell contents changed and will use an ideal cell height-to-
width ratio when calculating new sizes.
To configure the sizing mode for headers and rows and for columns that do not override the control value,
set one or more of the following DataGridView properties:
z ColumnHeadersHeightSizeMode
z RowHeadersWidthSizeMode
z AutoSizeColumnsMode
z AutoSizeRowsMode [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.autosizerowsmode(VS.80).aspx ]
To override the control's column sizing mode for an individual column, set its AutoSizeMode property to a
value other than NotSet [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewautosizecolumnmode(VS.80).aspx ] . The sizing mode for a
column is actually determined by its InheritedAutoSizeMode [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcolumn.inheritedautosizemode(VS.80).aspx ] property. The
value of this property is based on the column's AutoSizeMode property value unless that value is NotSet,
in which case the control's AutoSizeColumnsMode value is inherited.
Use content-based automatic resizing with caution when working with large amounts of data. To avoid
performance penalties, use the automatic sizing modes that calculate sizes based only on the displayed
rows rather than analyzing every row in the control. For maximum performance, use programmatic resizing
instead so that you can resize at specific times, such as immediately after new data is loaded.
Content-based automatic sizing modes do not affect rows, columns, or headers that you have hidden by
setting the row or column Visible [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewband.visible(VS.80).aspx ] property or the control
RowHeadersVisible [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.rowheadersvisible(VS.80).aspx ] or ColumnHeadersVisible
[ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview.columnheadersvisible
(VS.80).aspx ] properties to false. For example, if a column is hidden after it is automatically sized to fit a
large cell value, the hidden column will not change its size if the row containing the large cell value is
deleted. Automatic sizing does not occur when visibility changes, so changing the column Visible
[ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridviewcolumn.visible
(VS.80).aspx ] property back to true will not force it to recalculate its size based on its current contents.
Programmatic content-based resizing affects rows, columns, and headers regardless of their visibility.
Programmatic Resizing
When automatic sizing is disabled, you can programmatically set the exact width or height of rows,
columns, or headers through the following properties:
z System.Windows.Forms.DataGridView.RowHeadersWidth [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.rowheaderswidth(VS.80).aspx ]
z System.Windows.Forms.DataGridView.ColumnHeadersHeight [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.columnheadersheight(VS.80).aspx ]
z System.Windows.Forms.DataGridViewRow.Height [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewrow.height(VS.80).aspx ]
z System.Windows.Forms.DataGridViewColumn.Width
You can also programmatically resize rows, columns, and headers to fit their contents using the following
methods:
z AutoResizeColumn
z AutoResizeColumns
z AutoResizeColumnHeadersHeight [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.autoresizecolumnheadersheight(VS.80).aspx ]
z AutoResizeRow [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.autoresizerow(VS.80).aspx ]
http://msdn2.microsoft.com/en-us/library/74b2wakt(vs.80,d=printer).aspx 5/23/2007
Sizing Options in the Windows Forms DataGridView Control Page 5 of 6
z AutoResizeRows [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.autoresizerows(VS.80).aspx ]
z AutoResizeRowHeadersWidth [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.autoresizerowheaderswidth(VS.80).aspx ]
These methods will resize rows, columns, or headers once rather than configuring them for continuous
resizing. The new sizes are automatically calculated to display all cell contents without clipping. When you
programmatically resize columns that have InheritedAutoSizeMode property values of Fill, however, the
calculated content-based widths are used to proportionally adjust the column FillWeight property values,
and the actually column widths are then calculated according to these new proportions so that all columns
fill the available display area of the control.
Programmatic resizing is useful to avoid performance penalties with continuous resizing. It is also useful to
provide initial sizes for user-resizable rows, columns, and headers, and for column fill mode.
You will typically call the programmatic resizing methods at specific times. For example, you might
programmatically resize all columns immediately after loading data, or you might programmatically resize a
specific row after a particular cell value has been modified.
You can customize sizing behaviors when working with derived DataGridView cell, row, and column types
by overriding the System.Windows.Forms.DataGridViewCell.GetPreferredSize
(System.Drawing.Graphics,System.Windows.Forms.DataGridViewCellStyle,System.Int32,System.Drawing.Size)
[ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridviewcell.getpreferredsize
(VS.80).aspx ] , System.Windows.Forms.DataGridViewRow.GetPreferredHeight
(System.Int32,System.Windows.Forms.DataGridViewAutoSizeRowMode,System.Boolean)
[ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridviewrow.getpreferredheight
(VS.80).aspx ] , or System.Windows.Forms.DataGridViewColumn.GetPreferredWidth
(System.Windows.Forms.DataGridViewAutoSizeColumnMode,System.Boolean)
[ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridviewcolumn.getpreferredwidth
(VS.80).aspx ] methods or by calling protected resizing method overloads in a derived DataGridView
control. The protected resizing method overloads are designed to work in pairs to achieve an ideal cell
height-to-width ratio, avoiding overly wide or tall cells. For example, if you call the AutoResizeRows
(DataGridViewAutoSizeRowsMode,Boolean) overload of the AutoResizeRows method and pass in a
value of false for the Boolean [ http://msdn2.microsoft.com/en-us/library/system.boolean(VS.80).aspx ]
parameter, the overload will calculate the ideal heights and widths for cells in the row, but it will adjust the
row heights only. You must then call the AutoResizeColumns method to adjust the column widths to the
calculated ideal.
The enumerations used by sizing properties and methods have similar values for content-based sizing. With
these values, you can limit which cells are used to calculate the preferred sizes. For all sizing enumerations,
values with names that refer to displayed cells limit their calculations to cells in displayed rows. Excluding
rows is useful to avoid a performance penalty when you are working with a large quantity of rows. You can
also restrict calculations to cell values in header or nonheader cells.
See Also
Tasks
How to: Set the Sizing Modes of the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/fd004dhd(VS.80).aspx ]
Reference
DataGridView [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview
(VS.80).aspx ]
System.Windows.Forms.DataGridView.AllowUserToResizeColumns [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.allowusertoresizecolumns(VS.80).aspx ]
System.Windows.Forms.DataGridView.AllowUserToResizeRows [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.allowusertoresizerows(VS.80).aspx ]
System.Windows.Forms.DataGridView.ColumnHeadersHeightSizeMode [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.columnheadersheightsizemode(VS.80).aspx ]
System.Windows.Forms.DataGridView.RowHeadersWidthSizeMode [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.rowheaderswidthsizemode(VS.80).aspx ]
System.Windows.Forms.DataGridViewBand.Resizable [ http://msdn2.microsoft.com/en-
http://msdn2.microsoft.com/en-us/library/74b2wakt(vs.80,d=printer).aspx 5/23/2007
Sizing Options in the Windows Forms DataGridView Control Page 6 of 6
us/library/system.windows.forms.datagridviewband.resizable(VS.80).aspx ]
System.Windows.Forms.DataGridView.AutoSizeColumnsMode [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.autosizecolumnsmode(VS.80).aspx ]
System.Windows.Forms.DataGridView.AutoSizeRowsMode [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.autosizerowsmode(VS.80).aspx ]
System.Windows.Forms.DataGridViewColumn.AutoSizeMode [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcolumn.autosizemode(VS.80).aspx ]
System.Windows.Forms.DataGridViewColumn.InheritedAutoSizeMode [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcolumn.inheritedautosizemode(VS.80).aspx ]
System.Windows.Forms.DataGridView.RowHeadersWidth [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.rowheaderswidth(VS.80).aspx ]
System.Windows.Forms.DataGridView.ColumnHeadersHeight [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.columnheadersheight(VS.80).aspx ]
System.Windows.Forms.DataGridViewRow.Height [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewrow.height(VS.80).aspx ]
System.Windows.Forms.DataGridViewColumn.Width [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcolumn.width(VS.80).aspx ]
System.Windows.Forms.DataGridView.AutoResizeColumn [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.autoresizecolumn(VS.80).aspx ]
System.Windows.Forms.DataGridView.AutoResizeColumns [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.autoresizecolumns(VS.80).aspx ]
System.Windows.Forms.DataGridView.AutoResizeColumnHeadersHeight [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.autoresizecolumnheadersheight(VS.80).aspx ]
System.Windows.Forms.DataGridView.AutoResizeRow [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.autoresizerow(VS.80).aspx ]
System.Windows.Forms.DataGridView.AutoResizeRows [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.autoresizerows(VS.80).aspx ]
System.Windows.Forms.DataGridView.AutoResizeRowHeadersWidth [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.autoresizerowheaderswidth(VS.80).aspx ]
DataGridViewAutoSizeRowMode [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewautosizerowmode(VS.80).aspx ]
DataGridViewAutoSizeRowsMode [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewautosizerowsmode(VS.80).aspx ]
DataGridViewAutoSizeColumnMode [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewautosizecolumnmode(VS.80).aspx ]
DataGridViewAutoSizeColumnsMode [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewautosizecolumnsmode(VS.80).aspx ]
DataGridViewColumnHeadersHeightSizeMode [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcolumnheadersheightsizemode(VS.80).aspx ]
DataGridViewRowHeadersWidthSizeMode [ http://msdn2.microsoft.com/en-us/library/ms159167
(VS.80).aspx ]
Concepts
Column Fill Mode in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/ms171605(VS.80).aspx ]
Other Resources
Resizing Columns and Rows in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/ms171604(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/74b2wakt(vs.80,d=printer).aspx 5/23/2007
Column Fill Mode in the Windows Forms DataGridView Control Page 1 of 8
Each column can have a different size mode, but any columns with a size mode of Fill
[ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridviewautosizecolumnmode
(VS.80).aspx ] will share the display-area width that is not used by the other columns. This width is divided
among the fill-mode columns in proportions relative to their FillWeight [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcolumn.fillweight(VS.80).aspx ] property values. For
example, if two columns have FillWeight values of 100 and 200, the first column will be half as wide as
the second column.
Unlike sizing modes that resize based on cell contents, fill mode does not prevent users from resizing
columns that have Resizable [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcolumn.resizable(VS.80).aspx ] property values of true.
When a user resizes a fill-mode column, any fill-mode columns after the resized column (to the right if
RightToLeft [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.control.righttoleft
(VS.80).aspx ] is false; otherwise, to the left) are also resized to compensate for the change in the
available width. If there are no fill-mode columns after the resized column, then all other fill-mode columns
in the control are resized to compensate. If there are no other fill-mode columns in the control, the resize is
ignored. If a column that is not in fill mode is resized, all fill-mode columns in the control change sizes to
compensate.
After resizing a fill-mode column, the FillWeight values for all columns that changed are adjusted
proportionally. For example, if four fill-mode columns have FillWeight values of 100, resizing the second
column to half its original width will result in FillWeight values of 100, 50, 125, and 125. Resizing a
column that is not in fill mode will not change any FillWeight values because the fill-mode columns will
simply resize to compensate while retaining the same proportions.
You can initialize FillWeight values for fill-mode columns by using the DataGridView automatic resizing
methods, such as the AutoResizeColumns [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.autoresizecolumns(VS.80).aspx ] method. This method first
calculates the widths required by columns to display their contents. Next, the control adjusts the
FillWeight values for all fill-mode columns so that their proportions match the proportions of the calculated
widths. Finally, the control resizes the fill-mode columns using the new FillWeight proportions so that all
columns in the control fill the available horizontal space.
Example
By using appropriate values for the AutoSizeMode, MinimumWidth, FillWeight, and Resizable
http://msdn2.microsoft.com/en-us/library/ms171605(vs.80,d=printer).aspx 5/23/2007
Column Fill Mode in the Windows Forms DataGridView Control Page 2 of 8
properties, you can customize the column-sizing behaviors for many different scenarios.
The following demonstration code enables you to experiment with different values for the AutoSizeMode,
FillWeight, and MinimumWidth properties of different columns. In this example, a DataGridView
control is bound to its own Columns [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.columns(VS.80).aspx ] collection, and one column is bound
to each of the HeaderText [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcolumn.headertext(VS.80).aspx ] , AutoSizeMode,
FillWeight, MinimumWidth, and Width [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcolumn.width(VS.80).aspx ] properties. Each of the columns
is also represented by a row in the control, and changing values in a row will update the properties of the
corresponding column so that you can see how the values interact.
Imports System
Imports System.ComponentModel
Imports System.Reflection
Imports System.Windows.Forms
<STAThread()> _
Public Shared Sub Main()
Application.Run(New Form1())
End Sub
End Sub
http://msdn2.microsoft.com/en-us/library/ms171605(vs.80,d=printer).aspx 5/23/2007
Column Fill Mode in the Windows Forms DataGridView Control Page 3 of 8
' Create and initialize a column, using a combo box column for
' enumeration properties, a check box column for Boolean properties,
' and a text box column otherwise.
Dim column As DataGridViewColumn
Dim valueType As Type = propertyInfo1.PropertyType
If valueType.IsEnum Then
End Sub
End Sub
http://msdn2.microsoft.com/en-us/library/ms171605(vs.80,d=printer).aspx 5/23/2007
Column Fill Mode in the Windows Forms DataGridView Control Page 4 of 8
Handles dataGridView1.ColumnWidthChanged
End Sub
' For combo box and check box cells, commit any value change as soon
' as it is made rather than waiting for the focus to leave the cell.
If Not dataGridView1.CurrentCell.OwningColumn.GetType() _
.Equals(GetType(DataGridViewTextBoxColumn)) Then
dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit)
End If
End Sub
dataGridView1.Rows(e.RowIndex).ErrorText = e.Exception.Message
e.Cancel = True
Else
' Rethrow any exceptions that aren't related to the user input.
e.ThrowException = True
End If
End Sub
' Ensure that the error icon in the row header is hidden.
dataGridView1.Rows(e.RowIndex).ErrorText = ""
End Sub
End Sub
End Class
http://msdn2.microsoft.com/en-us/library/ms171605(vs.80,d=printer).aspx 5/23/2007
Column Fill Mode in the Windows Forms DataGridView Control Page 5 of 8
C# Copy Code
using System;
using System.ComponentModel;
using System.Reflection;
using System.Windows.Forms;
public Form1()
{
dataGridView1.Dock = DockStyle.Fill;
Controls.Add(dataGridView1);
InitializeDataGridView();
Width *= 2;
Text = "Column Fill-Mode Demo";
}
http://msdn2.microsoft.com/en-us/library/ms171605(vs.80,d=printer).aspx 5/23/2007
Column Fill Mode in the Windows Forms DataGridView Control Page 6 of 8
http://msdn2.microsoft.com/en-us/library/ms171605(vs.80,d=printer).aspx 5/23/2007
Column Fill Mode in the Windows Forms DataGridView Control Page 7 of 8
z Change the size of the form. Observe how columns change their widths while retaining the proportions
indicated by the FillWeight property values.
z Change the column sizes by dragging the column dividers with the mouse. Observe how the
FillWeight values change.
z Change the MinimumWidth value for one column, then drag to resize the form. Observe how, when
you make the form small enough, the Width values do not go below the MinimumWidth values.
z Change the MinimumWidth values for all columns to large numbers so that the combined values
exceed the width of the control. Observe how the horizontal scroll bar appears.
http://msdn2.microsoft.com/en-us/library/ms171605(vs.80,d=printer).aspx 5/23/2007
Column Fill Mode in the Windows Forms DataGridView Control Page 8 of 8
z Change the AutoSizeMode values for some columns. Observe the effect when you resize columns or
the form.
For information about building this example from the command line for Visual Basic or Visual C#, see
Building from the Command Line (Visual Basic) [ http://msdn2.microsoft.com/en-us/library/25fz1td5
(VS.80).aspx ] or Command-Line Building [ http://msdn2.microsoft.com/en-us/library/78f4aasd
(VS.80).aspx ] . You can also build this example in Visual Studio by pasting the code into a new project. For
more information, see How to: Compile and Run a Complete Windows Forms Code Example Using Visual
Studio [ http://msdn2.microsoft.com/en-us/bb129228(vs.80).aspx ] and How to: Compile and Run a
Complete Windows Forms Code Example Using Visual Studio [ http://msdn2.microsoft.com/en-
us/bb129228(vs.90).aspx ] .
See Also
Reference
DataGridView [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview
(VS.80).aspx ]
System.Windows.Forms.DataGridView.AutoResizeColumns [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.autoresizecolumns(VS.80).aspx ]
System.Windows.Forms.DataGridView.AutoSizeColumnsMode [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.autosizecolumnsmode(VS.80).aspx ]
DataGridViewAutoSizeColumnsMode [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewautosizecolumnsmode(VS.80).aspx ]
DataGridViewColumn [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcolumn(VS.80).aspx ]
System.Windows.Forms.DataGridViewColumn.InheritedAutoSizeMode [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcolumn.inheritedautosizemode(VS.80).aspx ]
System.Windows.Forms.DataGridViewColumn.AutoSizeMode [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcolumn.autosizemode(VS.80).aspx ]
DataGridViewAutoSizeColumnMode [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewautosizecolumnmode(VS.80).aspx ]
System.Windows.Forms.DataGridViewColumn.FillWeight [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcolumn.fillweight(VS.80).aspx ]
System.Windows.Forms.DataGridViewColumn.MinimumWidth [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcolumn.minimumwidth(VS.80).aspx ]
System.Windows.Forms.DataGridViewColumn.Width [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcolumn.width(VS.80).aspx ]
System.Windows.Forms.DataGridViewColumn.Resizable [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcolumn.resizable(VS.80).aspx ]
System.Windows.Forms.Control.RightToLeft [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.control.righttoleft(VS.80).aspx ]
Other Resources
Resizing Columns and Rows in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/ms171604(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/ms171605(vs.80,d=printer).aspx 5/23/2007
How to: Set the Sizing Modes of the Windows Forms DataGridView Control Page 1 of 5
C# Copy Code
DataGridViewTextBoxColumn idColumn =
new DataGridViewTextBoxColumn();
idColumn.HeaderText = "ID";
idColumn.AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
idColumn.Resizable = DataGridViewTriState.False;
idColumn.ReadOnly = true;
idColumn.Width = 20;
C# Copy Code
DataGridViewTextBoxColumn titleColumn =
new DataGridViewTextBoxColumn();
titleColumn.HeaderText = "Title";
titleColumn.AutoSizeMode =
DataGridViewAutoSizeColumnMode.AllCellsExceptHeader;
http://msdn2.microsoft.com/en-us/library/fd004dhd(vs.80,d=printer).aspx 5/23/2007
How to: Set the Sizing Modes of the Windows Forms DataGridView Control Page 2 of 5
dataGridView1.AutoSizeColumnsMode = _
DataGridViewAutoSizeColumnsMode.Fill
C# Copy Code
dataGridView1.AutoSizeColumnsMode =
DataGridViewAutoSizeColumnsMode.Fill;
DataGridViewTextBoxColumn subTitleColumn =
new DataGridViewTextBoxColumn();
subTitleColumn.HeaderText = "Subtitle";
subTitleColumn.MinimumWidth = 50;
subTitleColumn.FillWeight = 100;
DataGridViewTextBoxColumn summaryColumn =
new DataGridViewTextBoxColumn();
summaryColumn.HeaderText = "Summary";
summaryColumn.MinimumWidth = 50;
summaryColumn.FillWeight = 200;
DataGridViewTextBoxColumn contentColumn =
new DataGridViewTextBoxColumn();
contentColumn.HeaderText = "Content";
contentColumn.MinimumWidth = 50;
contentColumn.FillWeight = 300;
Example
The following complete code example provides a demonstration application that can help you
understand the sizing options described in this topic.
Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Data
http://msdn2.microsoft.com/en-us/library/fd004dhd(vs.80,d=printer).aspx 5/23/2007
How to: Set the Sizing Modes of the Windows Forms DataGridView Control Page 3 of 5
Imports System.Drawing
Imports System.Text
Imports System.Windows.Forms
<STAThreadAttribute()> _
Public Shared Sub Main()
Application.Run(New Form1())
End Sub
dataGridView1.AutoSizeColumnsMode = _
DataGridViewAutoSizeColumnsMode.Fill
dataGridView1.Columns.AddRange(New DataGridViewTextBoxColumn() { _
idColumn, titleColumn, subTitleColumn, _
summaryColumn, contentColumn})
dataGridView1.Rows.Add(New String() {"1", _
"A Short Title", "A Longer SubTitle", _
"A short description of the main point.", _
"The full contents of the topic, with detailed examples."})
MyBase.OnLoad(e)
End Sub
End Class
C# Copy Code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
http://msdn2.microsoft.com/en-us/library/fd004dhd(vs.80,d=printer).aspx 5/23/2007
How to: Set the Sizing Modes of the Windows Forms DataGridView Control Page 4 of 5
Application.Run(new Form1());
}
public Form1()
{
dataGridView1.Dock = DockStyle.Fill;
Controls.Add(dataGridView1);
Width *= 2;
Text = "DataGridView Sizing Scenarios";
}
DataGridViewTextBoxColumn titleColumn =
new DataGridViewTextBoxColumn();
titleColumn.HeaderText = "Title";
titleColumn.AutoSizeMode =
DataGridViewAutoSizeColumnMode.AllCellsExceptHeader;
dataGridView1.AutoSizeColumnsMode =
DataGridViewAutoSizeColumnsMode.Fill;
DataGridViewTextBoxColumn subTitleColumn =
new DataGridViewTextBoxColumn();
subTitleColumn.HeaderText = "Subtitle";
subTitleColumn.MinimumWidth = 50;
subTitleColumn.FillWeight = 100;
DataGridViewTextBoxColumn summaryColumn =
new DataGridViewTextBoxColumn();
summaryColumn.HeaderText = "Summary";
summaryColumn.MinimumWidth = 50;
summaryColumn.FillWeight = 200;
DataGridViewTextBoxColumn contentColumn =
new DataGridViewTextBoxColumn();
contentColumn.HeaderText = "Content";
contentColumn.MinimumWidth = 50;
contentColumn.FillWeight = 300;
dataGridView1.Columns.AddRange(new DataGridViewTextBoxColumn[] {
idColumn, titleColumn, subTitleColumn,
summaryColumn, contentColumn });
dataGridView1.Rows.Add(new String[] { "1",
"A Short Title", "A Longer SubTitle",
"A short description of the main point.",
"The full contents of the topic, with detailed examples." });
base.OnLoad(e);
}
}
z Change the size of the form. Observe how the fill-mode columns change their widths while
retaining the proportions indicated by the FillWeight property values. Observe how a column's
MinimumWidth prevents it from changing when the form is too small.
z Change the column sizes by dragging the column dividers with the mouse. Observe how some
columns cannot be resized, and how resizable columns cannot be made narrower than their
minimum widths.
http://msdn2.microsoft.com/en-us/library/fd004dhd(vs.80,d=printer).aspx 5/23/2007
How to: Set the Sizing Modes of the Windows Forms DataGridView Control Page 5 of 5
For information about building this example from the command line for Visual Basic or Visual C#, see
Building from the Command Line (Visual Basic) [ http://msdn2.microsoft.com/en-us/library/25fz1td5
(VS.80).aspx ] or Command-Line Building [ http://msdn2.microsoft.com/en-us/library/78f4aasd
(VS.80).aspx ] . You can also build this example in Visual Studio by pasting the code into a new project.
For more information, see How to: Compile and Run a Complete Windows Forms Code Example Using
Visual Studio [ http://msdn2.microsoft.com/en-us/bb129228(vs.80).aspx ] and How to: Compile and
Run a Complete Windows Forms Code Example Using Visual Studio [ http://msdn2.microsoft.com/en-
us/bb129228(vs.90).aspx ] .
See Also
Reference
DataGridView [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview
(VS.80).aspx ]
System.Windows.Forms.DataGridViewColumn.AutoSizeMode [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcolumn.autosizemode(VS.80).aspx ]
DataGridViewAutoSizeColumnMode [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewautosizecolumnmode(VS.80).aspx ]
System.Windows.Forms.DataGridViewColumn.Resizable [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcolumn.resizable(VS.80).aspx ]
System.Windows.Forms.DataGridViewColumn.ReadOnly [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcolumn.readonly(VS.80).aspx ]
System.Windows.Forms.DataGridViewColumn.Width [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcolumn.width(VS.80).aspx ]
System.Windows.Forms.DataGridViewColumn.FillWeight [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcolumn.fillweight(VS.80).aspx ]
System.Windows.Forms.DataGridViewColumn.MinimumWidth [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcolumn.minimumwidth(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/fd004dhd(vs.80,d=printer).aspx 5/23/2007
How to: Programmatically Resize Cells to Fit Content in the Windows Forms DataGridVi... Page 1 of 9
Typically, you will programmatically adjust DataGridView elements to fit their content only when you load
new data from a data source or when the user has edited a value. This is useful to optimize performance,
but it is also useful when you want to enable your users to manually resize rows and columns with the
mouse.
The following code example demonstrates the options available to you for programmatic resizing.
Example
AddButton(Button1, "Reset")
AddButton(Button2, "Change Column 3 Header")
AddButton(Button3, "Change Meatloaf Recipe")
AddButton(Button10, "Change Restaurant 2")
AddButtonsForProgrammaticResizing()
End Sub
Me.AutoSize = True
Me.Text = Me.GetType().Name
Me.Controls.Add(FlowLayoutPanel1)
End Sub
http://msdn2.microsoft.com/en-us/library/ff173xd4(vs.80,d=printer).aspx 5/23/2007
How to: Programmatically Resize Cells to Fit Content in the Windows Forms DataGridVi... Page 2 of 9
FlowLayoutPanel1.Controls.Add(directions)
End Sub
AddColumns()
PopulateRows()
shortMode = False
boringRecipe = True
End Sub
DataGridView1.Columns(0).Name = "Recipe"
DataGridView1.Columns(1).Name = "Category"
DataGridView1.Columns(2).Name = thirdColumnHeader
DataGridView1.Columns(3).Name = "Rating"
End Sub
http://msdn2.microsoft.com/en-us/library/ff173xd4(vs.80,d=printer).aspx 5/23/2007
How to: Programmatically Resize Cells to Fit Content in the Windows Forms DataGridVi... Page 3 of 9
End Sub
button.Text = buttonLabel
button.AutoSize = True
button.TabIndex = FlowLayoutPanel1.Controls.Count
FlowLayoutPanel1.Controls.Add(button)
End Sub
Controls.Remove(DataGridView1)
DataGridView1.Size = startingSize
DataGridView1.Dispose()
InitializeDataGridView(Nothing, Nothing)
End Sub
Toggle(shortMode)
If shortMode Then DataGridView1.Columns(2).HeaderText = "S" _
Else DataGridView1.Columns(2).HeaderText = thirdColumnHeader
End Sub
Toggle(boringRecipe)
If boringRecipe Then
SetMeatloaf(boringMeatloaf, boringMeatloafRanking)
Else
Dim greatMeatloafRecipe As String = "1 lb. lean ground beef, " _
& "1/2 cup bread crumbs, 1/4 cup ketchup," _
& "1/3 tsp onion powder, " _
& "1 clove of garlic, 1/2 pack onion soup mix " _
& " dash of your favorite BBQ Sauce"
SetMeatloaf(greatMeatloafRecipe, "***")
End If
End Sub
DataGridView1.Rows(0).Cells(2).Value = recipe
DataGridView1.Rows(0).Cells(3).Value = rating
End Sub
If DataGridView1.Rows(2).HeaderCell.Value.Equals(otherRestaurant) Then
DataGridView1.Rows(2).HeaderCell.Value = _
"Restaurant 2"
Else
DataGridView1.Rows(2).HeaderCell.Value = _
otherRestaurant
End If
http://msdn2.microsoft.com/en-us/library/ff173xd4(vs.80,d=printer).aspx 5/23/2007
How to: Programmatically Resize Cells to Fit Content in the Windows Forms DataGridVi... Page 4 of 9
End Sub
' The following code example resizes the second column to fit.
Private Sub SizeThirdColumnHeader(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Button4.Click
DataGridView1.AutoResizeColumn( _
2, DataGridViewAutoSizeColumnMode.ColumnHeader)
End Sub
' The following code example resizes the second column to fit
' the header
' text, but it leaves the widths of the
' row headers and columns unchanged.
Private Sub SizeColumnHeaders(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Button5.Click
DataGridView1.AutoResizeColumnHeadersHeight(2)
End Sub
' The following code example resizes all the columns to fit the
' header text and column contents.
Private Sub SizeAllColumns(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Button6.Click
DataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells)
End Sub
End Sub
' The following code example resizes the first displayed row
' to fit it's header.
Private Sub SizeFirstRowHeaderToAllHeaders(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Button8.Click
DataGridView1.AutoResizeRowHeadersWidth( _
DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders)
End Sub
' Size all the rows, including their headers and columns.
Private Sub SizeAllRowsAndTheirHeaders(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Button9.Click
DataGridView1.AutoResizeRows(DataGridViewAutoSizeRowsMode.AllCells)
End Sub
DataGridView1.AutoResizeRows(DataGridViewAutoSizeRowsMode.AllCellsExceptHeaders)
End Sub
#End Region
End Class
http://msdn2.microsoft.com/en-us/library/ff173xd4(vs.80,d=printer).aspx 5/23/2007
How to: Programmatically Resize Cells to Fit Content in the Windows Forms DataGridVi... Page 5 of 9
C# Copy Code
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
public ProgrammaticSizing()
{
InitializeComponent();
AddDirections();
this.Load += new EventHandler(InitializeDataGridView);
AddButton(button1, "Reset",
new EventHandler(ResetToDisorder));
AddButton(button2, "Change Column 3 Header",
new EventHandler(ChangeColumn3Header));
AddButton(button3, "Change Meatloaf Recipe",
new EventHandler(ChangeMeatloafRecipe));
AddButton(button10, "Change Restaurant 2",
new EventHandler(ChangeRestaurant));
AddButtonsForProgrammaticResizing();
}
this.AutoSize = true;
this.Controls.Add(this.flowLayoutPanel1);
this.Text = this.GetType().Name;
}
flowLayoutPanel1.Controls.Add(directions);
}
#endregion
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.Run(new ProgrammaticSizing());
}
http://msdn2.microsoft.com/en-us/library/ff173xd4(vs.80,d=printer).aspx 5/23/2007
How to: Programmatically Resize Cells to Fit Content in the Windows Forms DataGridVi... Page 6 of 9
AddColumns();
PopulateRows();
shortMode = false;
boringRecipe = true;
}
DataGridViewCellStyle columnHeaderStyle =
new DataGridViewCellStyle();
columnHeaderStyle.BackColor = Color.Aqua;
columnHeaderStyle.Font = new Font("Verdana", 10,
FontStyle.Bold);
dataGridView1.ColumnHeadersDefaultCellStyle =
columnHeaderStyle;
dataGridView1.Columns[0].Name = "Recipe";
dataGridView1.Columns[1].Name = "Category";
dataGridView1.Columns[2].Name = thirdColumnHeader;
dataGridView1.Columns[3].Name = "Rating";
}
http://msdn2.microsoft.com/en-us/library/ff173xd4(vs.80,d=printer).aspx 5/23/2007
How to: Programmatically Resize Cells to Fit Content in the Windows Forms DataGridVi... Page 7 of 9
{
button.Text = buttonLabel;
button.AutoSize = true;
flowLayoutPanel1.Controls.Add(button);
button.Click += handler;
}
if (boringRecipe)
SetMeatloaf(boringMeatloaf, boringMeatloafRanking);
else
{
string greatMeatloafRecipe =
"1 lb. lean ground beef, "
+ "1/2 cup bread crumbs, 1/4 cup ketchup,"
+ "1/3 tsp onion powder, "
+ "1 clove of garlic, 1/2 pack onion soup mix "
+ " dash of your favorite BBQ Sauce";
SetMeatloaf(greatMeatloafRecipe, "***");
}
}
http://msdn2.microsoft.com/en-us/library/ff173xd4(vs.80,d=printer).aspx 5/23/2007
How to: Programmatically Resize Cells to Fit Content in the Windows Forms DataGridVi... Page 8 of 9
new EventHandler(SizeThirdRow));
AddButton(button8, "Size First Row Header Using All Headers",
new EventHandler(SizeFirstRowHeaderToAllHeaders));
AddButton(button9, "Size All Rows and Row Headers",
new EventHandler(SizeAllRowsAndTheirHeaders));
AddButton(button11, "Size All Rows ",
new EventHandler(SizeAllRows));
}
For information about building this example from the command line for Visual Basic or Visual C#, see
Building from the Command Line (Visual Basic) [ http://msdn2.microsoft.com/en-us/library/25fz1td5
(VS.80).aspx ] or Command-Line Building [ http://msdn2.microsoft.com/en-us/library/78f4aasd
(VS.80).aspx ] . You can also build this example in Visual Studio by pasting the code into a new project.
For more information, see How to: Compile and Run a Complete Windows Forms Code Example Using
Visual Studio [ http://msdn2.microsoft.com/en-us/bb129228(vs.80).aspx ] and How to: Compile and
Run a Complete Windows Forms Code Example Using Visual Studio [ http://msdn2.microsoft.com/en-
us/bb129228(vs.90).aspx ] .
See Also
Tasks
How to: Automatically Resize Cells When Content Changes in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/f71f07b5(VS.80).aspx ]
http://msdn2.microsoft.com/en-us/library/ff173xd4(vs.80,d=printer).aspx 5/23/2007
How to: Programmatically Resize Cells to Fit Content in the Windows Forms DataGridVi... Page 9 of 9
Reference
DataGridView [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview
(VS.80).aspx ]
System.Windows.Forms.DataGridView.AutoResizeColumn [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.autoresizecolumn(VS.80).aspx ]
System.Windows.Forms.DataGridView.AutoResizeColumns [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.autoresizecolumns(VS.80).aspx ]
System.Windows.Forms.DataGridView.AutoResizeColumnHeadersHeight [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.autoresizecolumnheadersheight(VS.80).aspx ]
System.Windows.Forms.DataGridView.AutoResizeRow [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.autoresizerow(VS.80).aspx ]
System.Windows.Forms.DataGridView.AutoResizeRows [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.autoresizerows(VS.80).aspx ]
System.Windows.Forms.DataGridView.AutoResizeRowHeadersWidth [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.autoresizerowheaderswidth(VS.80).aspx ]
DataGridViewAutoSizeRowMode [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewautosizerowmode(VS.80).aspx ]
DataGridViewAutoSizeRowsMode [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewautosizerowsmode(VS.80).aspx ]
DataGridViewAutoSizeColumnMode [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewautosizecolumnmode(VS.80).aspx ]
DataGridViewAutoSizeColumnsMode [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewautosizecolumnsmode(VS.80).aspx ]
DataGridViewColumnHeadersHeightSizeMode [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcolumnheadersheightsizemode(VS.80).aspx ]
DataGridViewRowHeadersWidthSizeMode [ http://msdn2.microsoft.com/en-us/library/ms159167
(VS.80).aspx ]
Concepts
Sizing Options in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/74b2wakt(VS.80).aspx ]
Other Resources
Resizing Columns and Rows in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/ms171604(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/ff173xd4(vs.80,d=printer).aspx 5/23/2007
Sorting Data in the Windows Forms DataGridView Control Page 1 of 1
In This Section
How to: Set the Sort Modes for Columns in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/8b9k0ktw(VS.80).aspx ]
Describes how to enable users to sort by columns that are not sortable by default.
How to: Customize Sorting in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/ms171608(VS.80).aspx ]
Describes how to sort data programmatically and how to customize sorting by using the
System.Windows.Forms.DataGridView.SortCompare [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.sortcompare(VS.80).aspx ] event or by implementing
the IComparer [ http://msdn2.microsoft.com/en-us/library/system.collections.icomparer
(VS.80).aspx ] interface.
Reference
DataGridView [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview
(VS.80).aspx ]
Provides reference documentation for the DataGridView control.
System.Windows.Forms.DataGridView.Sort [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.sort(VS.80).aspx ]
Provides reference documentation for the Sort method.
System.Windows.Forms.DataGridViewColumn.SortMode [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcolumn.sortmode(VS.80).aspx ]
Provides reference documentation for the SortMode property.
DataGridViewColumnSortMode [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcolumnsortmode(VS.80).aspx ]
Provides reference documentation for the DataGridViewColumnSortMode enumeration.
See Also
Concepts
Column Types in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/bxt3k60s(VS.80).aspx ]
Other Resources
DataGridView Control (Windows Forms) [ http://msdn2.microsoft.com/en-us/library/e0ywh3cz
(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/ms171607(vs.80,d=printer).aspx 5/24/2007
Column Sort Modes in the Windows Forms DataGridView Control Page 1 of 4
You might want to change the sort mode for a column that defaults to NotSortable if it contains values
that can be meaningfully ordered. For example, if you have a database column containing numbers that
represent item states, you can display these numbers as corresponding icons by binding an image column
to the database column. You can then change the numerical cell values into image display values in a
handler for the System.Windows.Forms.DataGridView.CellFormatting [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.cellformatting(VS.80).aspx ] event. In this case, setting the
SortMode property to Automatic will enable your users to sort the column. Automatic sorting will enable
your users to group items that have the same state even if the states corresponding to the numbers do not
have a natural sequence. Check box columns are another example where automatic sorting is useful for
grouping items in the same state.
You can sort a DataGridView programmatically by the values in any column or in multiple columns,
regardless of the SortMode settings. Programmatic sorting is useful when you want to provide your own
user interface (UI) for sorting or when you want to implement custom sorting. Providing your own sorting
UI is useful, for example, when you set the DataGridView selection mode to enable column header
selection. In this case, although the column headers cannot be used for sorting, you still want the headers
to display the appropriate sorting glyph, so you would set the SortMode property to Programmatic.
Columns set to programmatic sort mode do not automatically display a sorting glyph. For these columns,
you must display the glyph yourself by setting the
System.Windows.Forms.DataGridViewColumnHeaderCell.SortGlyphDirection
[ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcolumnheadercell.sortglyphdirection(VS.80).aspx ] property.
This is necessary if you want flexibility in custom sorting. For example, if you sort the DataGridView by
multiple columns, you might want to display multiple sorting glyphs or no sorting glyph.
Although you can programmatically sort a DataGridView by any column, some columns, such as button
http://msdn2.microsoft.com/en-us/library/95scxcdy(vs.80,d=printer).aspx 5/24/2007
Column Sort Modes in the Windows Forms DataGridView Control Page 2 of 4
columns, might not contain values that can be meaningfully ordered. For these columns, a SortMode
property setting of NotSortable indicates that it will never be used for sorting, so there is no need to
reserve space in the header for the sorting glyph.
When a DataGridView is sorted, you can determine both the sort column and the sort order by checking
the values of the SortedColumn [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.sortedcolumn(VS.80).aspx ] and SortOrder
[ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview.sortorder(VS.80).aspx ]
properties. These values are not meaningful after a custom sorting operation. For more information about
custom sorting, see the Custom Sorting section later in this topic.
When a DataGridView control containing both bound and unbound columns is sorted, the values in the
unbound columns cannot be maintained automatically. To maintain these values, you must implement
virtual mode by setting the VirtualMode [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.virtualmode(VS.80).aspx ] property to true and handling
the CellValueNeeded [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.cellvalueneeded(VS.80).aspx ] and CellValuePushed
[ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview.cellvaluepushed
(VS.80).aspx ] events. For more information, see How to: Implement Virtual Mode in the Windows Forms
DataGridView Control [ http://msdn2.microsoft.com/en-us/library/2b177d6d(VS.80).aspx ] . Sorting by
unbound columns in bound mode is not supported.
Programmatic Sorting
Note
When the DataGridView control is bound to an external data source by setting the DataSource
[ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview.datasource
(VS.80).aspx ] property, the Sort(DataGridViewColumn,ListSortDirection) method overload does
not work for unbound columns. Additionally, when the VirtualMode property is true, you can call this
overload only for bound columns. To determine whether a column is data-bound, check the
IsDataBound [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcolumn.isdatabound(VS.80).aspx ] property value.
Sorting unbound columns in bound mode is not supported.
Custom Sorting
You can customize DataGridView by using the Sort(IComparer) overload of the Sort method or by
handling the SortCompare [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.sortcompare(VS.80).aspx ] event.
The Sort(IComparer) method overload takes an instance of a class that implements the IComparer
[ http://msdn2.microsoft.com/en-us/library/system.collections.icomparer(VS.80).aspx ] interface as a
parameter. This overload is useful when you want to provide custom sorting; for example, when the values
in a column do not have a natural sort order or when the natural sort order is inappropriate. In this case,
you cannot use automatic sorting, but you might still want your users to sort by clicking the column
headers. You can call this overload in a handler for the ColumnHeaderMouseClick
[ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview.columnheadermouseclick
(VS.80).aspx ] event if you do not use column headers for selection.
http://msdn2.microsoft.com/en-us/library/95scxcdy(vs.80,d=printer).aspx 5/24/2007
Column Sort Modes in the Windows Forms DataGridView Control Page 3 of 4
Note
The Sort(IComparer) method overload works only when the DataGridView control is not bound to
an external data source and the VirtualMode property value is false. To customize sorting for
columns bound to an external data source, you must use the sorting operations provided by the data
source. In virtual mode, you must provide your own sorting operations for unbound columns.
To use the Sort(IComparer) method overload, you must create your own class that implements the
IComparer interface. This interface requires your class to implement the
System.Collections.IComparer.Compare(System.Object,System.Object) [ http://msdn2.microsoft.com/en-
us/library/system.collections.icomparer.compare(VS.80).aspx ] method, to which the DataGridView
passes DataGridViewRow [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewrow(VS.80).aspx ] objects as input when the Sort
(IComparer) method overload is called. With this, you can calculate the correct row ordering based on the
values in any column.
The Sort(IComparer) method overload does not set the SortedColumn and SortOrder properties, so
you must always set the
System.Windows.Forms.DataGridViewColumnHeaderCell.SortGlyphDirection property to display
the sorting glyph.
As an alternative to the Sort(IComparer) method overload, you can provide custom sorting by
implementing a handler for the SortCompare event. This event occurs when users click the headers of
columns configured for automatic sorting or when you call the Sort
(DataGridViewColumn,ListSortDirection) overload of the Sort method. The event occurs for each pair
of rows in the control, enabling you to calculate their correct order.
Note
The SortCompare event does not occur when the DataSource property is set or when the
VirtualMode property value is true.
See Also
Tasks
How to: Set the Sort Modes for Columns in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/8b9k0ktw(VS.80).aspx ]
Reference
DataGridView [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview
(VS.80).aspx ]
System.Windows.Forms.DataGridView.Sort [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.sort(VS.80).aspx ]
System.Windows.Forms.DataGridView.SortedColumn [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.sortedcolumn(VS.80).aspx ]
System.Windows.Forms.DataGridView.SortOrder [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.sortorder(VS.80).aspx ]
System.Windows.Forms.DataGridViewColumn.SortMode [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcolumn.sortmode(VS.80).aspx ]
System.Windows.Forms.DataGridViewColumnHeaderCell.SortGlyphDirection
[ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcolumnheadercell.sortglyphdirection(VS.80).aspx ]
Concepts
How to: Customize Sorting in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/ms171608(VS.80).aspx ]
Other Resources
Sorting Data in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/ms171607(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/95scxcdy(vs.80,d=printer).aspx 5/24/2007
Column Sort Modes in the Windows Forms DataGridView Control Page 4 of 4
http://msdn2.microsoft.com/en-us/library/95scxcdy(vs.80,d=printer).aspx 5/24/2007
How to: Set the Sort Modes for Columns in the Windows Forms DataGridView Control Page 1 of 2
The following procedure shows the Priority column from How to: Customize Data Formatting in the
Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-us/library/z1cc356h
(VS.80).aspx ] . This column is an image column and is not sortable by default. It contains actual cell
values that are strings, however, so it can be sorted automatically.
Me.dataGridView1.Columns("Priority").SortMode = _
DataGridViewColumnSortMode.Automatic
C# Copy Code
this.dataGridView1.Columns["Priority"].SortMode =
DataGridViewColumnSortMode.Automatic;
See Also
Reference
DataGridView [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview
(VS.80).aspx ]
System.Windows.Forms.DataGridViewColumn.SortMode [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcolumn.sortmode(VS.80).aspx ]
Concepts
Column Sort Modes in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/95scxcdy(VS.80).aspx ]
How to: Customize Sorting in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/ms171608(VS.80).aspx ]
Other Resources
Sorting Data in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/ms171607(VS.80).aspx ]
http://msdn2.microsoft.com/en-us/library/8b9k0ktw(vs.80,d=printer).aspx 5/24/2007
How to: Set the Sort Modes for Columns in the Windows Forms DataGridView Control Page 2 of 2
Community Content
http://msdn2.microsoft.com/en-us/library/8b9k0ktw(vs.80,d=printer).aspx 5/24/2007
How to: Customize Sorting in the Windows Forms DataGridView Control Page 1 of 10
The following code examples demonstrate these three approaches to custom sorting. For more information,
see Column Sort Modes in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/95scxcdy(VS.80).aspx ] .
Programmatic Sorting
The following code example demonstrates a programmatic sort using the SortOrder
[ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview.sortorder(VS.80).aspx ]
and SortedColumn [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.sortedcolumn(VS.80).aspx ] properties to determine the
direction of the sort, and the SortGlyphDirection [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcolumnheadercell.sortglyphdirection(VS.80).aspx ] property
to manually set the sort glyph. The Sort(DataGridViewColumn,ListSortDirection) overload of the Sort
method is used to sort data only in a single column.
Imports System
Imports System.ComponentModel
Imports System.Windows.Forms
sortButton.Dock = DockStyle.Bottom
sortButton.Text = "Sort"
Controls.Add(dataGridView1)
Controls.Add(sortButton)
Text = "DataGridView programmatic sort demo"
PopulateDataGridView()
End Sub
http://msdn2.microsoft.com/en-us/library/ms171608(vs.80,d=printer).aspx 5/24/2007
How to: Customize Sorting in the Windows Forms DataGridView Control Page 2 of 10
End Sub
End Class
C# Copy Code
using System;
using System.ComponentModel;
using System.Windows.Forms;
http://msdn2.microsoft.com/en-us/library/ms171608(vs.80,d=printer).aspx 5/24/2007
How to: Customize Sorting in the Windows Forms DataGridView Control Page 3 of 10
sortButton.Dock = DockStyle.Bottom;
sortButton.Text = "Sort";
Controls.Add(dataGridView1);
Controls.Add(sortButton);
Text = "DataGridView programmatic sort demo";
}
PopulateDataGridView();
base.OnLoad(e);
}
http://msdn2.microsoft.com/en-us/library/ms171608(vs.80,d=printer).aspx 5/24/2007
How to: Customize Sorting in the Windows Forms DataGridView Control Page 4 of 10
The following code example demonstrates custom sorting using a SortCompare event handler. The
selected DataGridViewColumn [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcolumn(VS.80).aspx ] is sorted and, if there are duplicate
values in the column, the ID column is used to determine the final order.
Imports System
Imports System.Windows.Forms
Me.PopulateDataGridView()
End Sub
http://msdn2.microsoft.com/en-us/library/ms171608(vs.80,d=printer).aspx 5/24/2007
How to: Customize Sorting in the Windows Forms DataGridView Control Page 5 of 10
End Sub
' Try to sort based on the contents of the cell in the current column.
e.SortResult = System.String.Compare(e.CellValue1.ToString(), _
e.CellValue2.ToString())
e.Handled = True
End Sub
End Class
C# Copy Code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
#endregion
class Form1 : Form
{
private DataGridView dataGridView1 = new DataGridView();
public Form1()
{
// Initialize the form.
// This code can be replaced with designer generated code.
dataGridView1.AllowUserToAddRows = false;
dataGridView1.Dock = DockStyle.Fill;
dataGridView1.SortCompare += new DataGridViewSortCompareEventHandler(
this.dataGridView1_SortCompare);
Controls.Add(this.dataGridView1);
this.Text = "DataGridView.SortCompare demo";
PopulateDataGridView();
}
http://msdn2.microsoft.com/en-us/library/ms171608(vs.80,d=printer).aspx 5/24/2007
How to: Customize Sorting in the Windows Forms DataGridView Control Page 6 of 10
The following code example demonstrates custom sorting using the Sort(IComparer) overload of the Sort
method, which takes an implementation of the IComparer [ http://msdn2.microsoft.com/en-
us/library/system.collections.icomparer(VS.80).aspx ] interface to perform a multiple-column sort.
Imports System
Imports System.Drawing
Imports System.Windows.Forms
FlowLayoutPanel1.FlowDirection = FlowDirection.TopDown
FlowLayoutPanel1.Location = New System.Drawing.Point(304, 0)
FlowLayoutPanel1.AutoSize = True
FlowLayoutPanel1.Controls.Add(RadioButton1)
FlowLayoutPanel1.Controls.Add(RadioButton2)
FlowLayoutPanel1.Controls.Add(Button1)
Button1.Text = "Sort"
RadioButton1.Text = "Ascending"
RadioButton2.Text = "Descending"
RadioButton1.Checked = True
Controls.Add(FlowLayoutPanel1)
Controls.Add(DataGridView1)
PopulateDataGridView()
http://msdn2.microsoft.com/en-us/library/ms171608(vs.80,d=printer).aspx 5/24/2007
How to: Customize Sorting in the Windows Forms DataGridView Control Page 7 of 10
End Sub
' Replace this with your own code to populate the DataGridView.
Private Sub PopulateDataGridView()
sortOrderModifier = 1
End If
End Sub
' If the Last Names are equal, sort based on the First Name.
If CompareResult = 0 Then
CompareResult = System.String.Compare( _
DataGridViewRow1.Cells(0).Value.ToString(), _
DataGridViewRow2.Cells(0).Value.ToString())
End If
Return CompareResult * sortOrderModifier
End Function
End Class
End Class
C# Copy Code
using System;
using System.Drawing;
using System.Windows.Forms;
http://msdn2.microsoft.com/en-us/library/ms171608(vs.80,d=printer).aspx 5/24/2007
How to: Customize Sorting in the Windows Forms DataGridView Control Page 8 of 10
#endregion
public Form1()
{
// Initialize the form.
// This code can be replaced with designer generated code.
AutoSize = true;
Text = "DataGridView IComparer sort demo";
FlowLayoutPanel1.FlowDirection = FlowDirection.TopDown;
FlowLayoutPanel1.Location = new System.Drawing.Point( 304, 0 );
FlowLayoutPanel1.AutoSize = true;
FlowLayoutPanel1.Controls.Add( RadioButton1 );
FlowLayoutPanel1.Controls.Add( RadioButton2 );
FlowLayoutPanel1.Controls.Add( Button1 );
Button1.Text = "Sort";
RadioButton1.Text = "Ascending";
RadioButton2.Text = "Descending";
RadioButton1.Checked = true;
Controls.Add( FlowLayoutPanel1 );
Controls.Add( DataGridView1 );
}
base.OnLoad( e );
}
http://msdn2.microsoft.com/en-us/library/ms171608(vs.80,d=printer).aspx 5/24/2007
How to: Customize Sorting in the Windows Forms DataGridView Control Page 9 of 10
// If the Last Names are equal, sort based on the First Name.
if ( CompareResult == 0 )
{
CompareResult = System.String.Compare(
DataGridViewRow1.Cells[0].Value.ToString(),
DataGridViewRow2.Cells[0].Value.ToString());
}
return CompareResult * sortOrderModifier;
}
}
}
For information about building these examples from the command line for Visual Basic or Visual C#, see
Building from the Command Line (Visual Basic) [ http://msdn2.microsoft.com/en-us/library/25fz1td5
(VS.80).aspx ] or Command-Line Building [ http://msdn2.microsoft.com/en-us/library/78f4aasd
(VS.80).aspx ] . You can also build this example in Visual Studio by pasting the code into a new project. For
more information, see How to: Compile and Run a Complete Windows Forms Code Example Using Visual
Studio [ http://msdn2.microsoft.com/en-us/bb129228(vs.80).aspx ] and How to: Compile and Run a
Complete Windows Forms Code Example Using Visual Studio [ http://msdn2.microsoft.com/en-
us/bb129228(vs.90).aspx ] .
See Also
Tasks
How to: Set the Sort Modes for Columns in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/8b9k0ktw(VS.80).aspx ]
Reference
DataGridView [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview
(VS.80).aspx ]
Concepts
Column Sort Modes in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/95scxcdy(VS.80).aspx ]
Other Resources
http://msdn2.microsoft.com/en-us/library/ms171608(vs.80,d=printer).aspx 5/24/2007
How to: Customize Sorting in the Windows Forms DataGridView Control Page 10 of 10
Community Content
http://msdn2.microsoft.com/en-us/library/ms171608(vs.80,d=printer).aspx 5/24/2007
Data Entry in the Windows Forms DataGridView Control Page 1 of 2
In This Section
How to: Specify the Edit Mode for the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/yztkd864(VS.80).aspx ]
Describes how to change the way users start editing cells.
How to: Specify Default Values for New Rows in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/b22t666e(VS.80).aspx ]
Describes how to prepopulate the row for new records to save data-entry time.
Using the Row for New Records in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/ka3w9f4d(VS.80).aspx ]
Describes the row for new records in detail, including information on hiding it, on customizing its
appearance, and on how it relates to the Rows [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.rows(VS.80).aspx ] collection.
Walkthrough: Handling Errors that Occur During Data Entry in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/t4a23xx4(VS.80).aspx ]
Describes how to handle data-entry errors that originate from the data source when the user
attempts to commit a new value.
Reference
DataGridView [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview
(VS.80).aspx ]
Provides reference documentation for the DataGridView control.
System.Windows.Forms.DataGridView.EditMode [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.editmode(VS.80).aspx ]
Provides reference documentation for the EditMode property.
System.Windows.Forms.DataGridView.DefaultValuesNeeded [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.defaultvaluesneeded(VS.80).aspx ]
Provides reference documentation for the DefaultValuesNeeded event.
System.Windows.Forms.DataGridView.DataError [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.dataerror(VS.80).aspx ]
Provides reference documentation for the DataError event.
System.Windows.Forms.DataGridView.CellValidating [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.cellvalidating(VS.80).aspx ]
Provides reference documentation for the CellValidating event.
Related Sections
http://msdn2.microsoft.com/en-us/library/ms171610(vs.80,d=printer).aspx 5/24/2007
Data Entry in the Windows Forms DataGridView Control Page 2 of 2
See Also
Concepts
Column Types in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/bxt3k60s(VS.80).aspx ]
Other Resources
DataGridView Control (Windows Forms) [ http://msdn2.microsoft.com/en-us/library/e0ywh3cz
(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/ms171610(vs.80,d=printer).aspx 5/24/2007
How to: Specify the Edit Mode for the Windows Forms DataGridView Control Page 1 of 2
In edit mode, the user can change the cell value and press ENTER to commit the change or ESC to revert
the cell to its original value.
You can configure a DataGridView control so that a cell enters edit mode as soon as it becomes the
current cell. The behavior of the ENTER and ESC keys is unchanged in this case, but the cell remains in edit
mode after the value is committed or reverted. You can also configure the control so that cells enter edit
mode only when users type in the cell or only when users press F2. Finally, you can prevent cells from
entering edit mode except when you call the BeginEdit [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.beginedit(VS.80).aspx ] method.
Me.dataGridView1.EditMode = DataGridViewEditMode.EditOnEnter
C# Copy Code
this.dataGridView1.EditMode = DataGridViewEditMode.EditOnEnter;
See Also
Reference
DataGridView [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview
(VS.80).aspx ]
System.Windows.Forms.DataGridView.EditMode [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.editmode(VS.80).aspx ]
http://msdn2.microsoft.com/en-us/library/yztkd864(vs.80,d=printer).aspx 5/24/2007
How to: Specify the Edit Mode for the Windows Forms DataGridView Control Page 2 of 2
Other Resources
Data Entry in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/ms171610(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/yztkd864(vs.80,d=printer).aspx 5/24/2007
How to: Specify Default Values for New Rows in the Windows Forms DataGridView Co... Page 1 of 2
The following code example demonstrates how to specify default values for new rows using the
DefaultValuesNeeded event.
Example
With e.Row
.Cells("Region").Value = "WA"
.Cells("City").Value = "Redmond"
.Cells("PostalCode").Value = "98052-6399"
.Cells("Region").Value = "NA"
.Cells("Country").Value = "USA"
.Cells("CustomerID").Value = NewCustomerId()
End With
End Sub
C# Copy Code
See Also
Reference
DataGridView [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview
(VS.80).aspx ]
http://msdn2.microsoft.com/en-us/library/b22t666e(vs.80,d=printer).aspx 5/24/2007
How to: Specify Default Values for New Rows in the Windows Forms DataGridView Co... Page 2 of 2
System.Windows.Forms.DataGridView.DefaultValuesNeeded [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.defaultvaluesneeded(VS.80).aspx ]
Concepts
Using the Row for New Records in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/ka3w9f4d(VS.80).aspx ]
Other Resources
Data Entry in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/ms171610(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/b22t666e(vs.80,d=printer).aspx 5/24/2007
Using the Row for New Records in the Windows Forms DataGridView Control Page 1 of 3
For the data bound case, the row for new records will be shown if the AllowUserToAddRows property of
the control and the System.ComponentModel.IBindingList.AllowNew [ http://msdn2.microsoft.com/en-
us/library/system.componentmodel.ibindinglist.allownew(VS.80).aspx ] property of the data source are
both true. If either is false then the row will not be shown.
When the user selects the row for new records as the current row, the DataGridView control raises the
DefaultValuesNeeded [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.defaultvaluesneeded(VS.80).aspx ] event.
The row for new records is contained in the DataGridView control's Rows
[ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview.rows(VS.80).aspx ]
collection but behaves differently in two respects:
z The row for new records cannot be removed from the Rows collection programmatically. An
InvalidOperationException [ http://msdn2.microsoft.com/en-
us/library/system.invalidoperationexception(VS.80).aspx ] is thrown if this is attempted. The user also
cannot delete the row for new records. The System.Windows.Forms.DataGridViewRowCollection.Clear
[ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridviewrowcollection.clear
(VS.80).aspx ] method does not remove this row from the Rows collection.
z No row can be added after the row for new records. An InvalidOperationException is raised if this
is attempted. As a result, the row for new records is always the last row in the DataGridView control.
The methods on DataGridViewRowCollection [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewrowcollection(VS.80).aspx ] that add rows—Add
[ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridviewrowcollection.add
(VS.80).aspx ] , AddCopy [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewrowcollection.addcopy(VS.80).aspx ] , and AddCopies
[ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewrowcollection.addcopies(VS.80).aspx ] —all call
insertion methods internally when the row for new records is present.
http://msdn2.microsoft.com/en-us/library/ka3w9f4d(vs.80,d=printer).aspx 5/24/2007
Using the Row for New Records in the Windows Forms DataGridView Control Page 2 of 3
When the row for new records is created, it is based on the row specified by the RowTemplate
[ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview.rowtemplate
(VS.80).aspx ] property. Any cell styles that are not specified for this row are inherited from other
properties. For more information about cell style inheritance, see Cell Styles in the Windows Forms
DataGridView Control [ http://msdn2.microsoft.com/en-us/library/1yef90x0(VS.80).aspx ] .
The initial values displayed by cells in the row for new records are retrieved from each cell's
DefaultNewRowValue [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcell.defaultnewrowvalue(VS.80).aspx ] property. For cells of
type DataGridViewImageCell [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewimagecell(VS.80).aspx ] , this property returns a placeholder
image. Otherwise, this property returns null. You can override this property to return a custom value.
However, these initial values can be replaced by a DefaultValuesNeeded event handler when focus enters
the row for new records.
The standard icons for this row's header, which are an arrow or an asterisk, are not exposed publicly. If you
want to customize the icons, you will need to create a custom DataGridViewRowHeaderCell
[ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridviewrowheadercell
(VS.80).aspx ] class.
If the row header cell has a string value set, and if there is not enough room for both the text and icon, the
icon is dropped first.
Sorting
In unbound mode, new records will always be added to the end of the DataGridView even if the user has
sorted the content of the DataGridView. The user will need to apply the sort again in order to sort the row
to the correct position; this behavior is similar to that of the ListView [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.listview(VS.80).aspx ] control.
In data bound and virtual modes, the insertion behavior when a sort is applied will be dependent on the
implementation of the data model. For ADO.NET, the row is immediately sorted into the correct position.
The row for new records is always created in the unselected state.
Virtual Mode
If you are implementing virtual mode, you will need to track when a row for new records is needed in the
data model and when to roll back the addition of the row. The exact implementation of this functionality
depends on the implementation of the data model and its transaction semantics, for example, whether
commit scope is at the cell or row level. For more information, see Virtual Mode in the Windows Forms
DataGridView Control [ http://msdn2.microsoft.com/en-us/library/ms171622(VS.80).aspx ] .
See Also
Tasks
How to: Specify Default Values for New Rows in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/b22t666e(VS.80).aspx ]
Reference
DataGridView [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview
(VS.80).aspx ]
System.Windows.Forms.DataGridView.DefaultValuesNeeded [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.defaultvaluesneeded(VS.80).aspx ]
http://msdn2.microsoft.com/en-us/library/ka3w9f4d(vs.80,d=printer).aspx 5/24/2007
Using the Row for New Records in the Windows Forms DataGridView Control Page 3 of 3
Other Resources
Data Entry in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/ms171610(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/ka3w9f4d(vs.80,d=printer).aspx 5/24/2007
Walkthrough: Validating Data in the Windows Forms DataGridView Control Page 1 of 7
In this walkthrough, you will retrieve rows from the Customers table in the Northwind sample database and
display them in a DataGridView control. When a user edits a cell in the CompanyName column and tries to
leave the cell, the CellValidating event handler will examine new company name string to make sure it is
not empty; if the new value is an empty string, the DataGridView will prevent the user's cursor from
leaving the cell until a non-empty string is entered.
To copy the code in this topic as a single listing, see How to: Validate Data in the Windows Forms
DataGridView Control [ http://msdn2.microsoft.com/en-us/library/7ehy30d4(VS.80).aspx ] .
Prerequisites
In order to complete this walkthrough, you will need:
z Access to a server that has the Northwind SQL Server sample database.
Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.Windows.Forms
End Sub
<br /><span space="preserve">...</span><br /> <STAThread()> _
http://msdn2.microsoft.com/en-us/library/ykdxa0bc(vs.80,d=printer).aspx 5/24/2007
Walkthrough: Validating Data in the Windows Forms DataGridView Control Page 2 of 7
End Class
C# Copy Code
using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
public Form1()
{
// Initialize the form.
this.dataGridView1.Dock = DockStyle.Fill;
this.Controls.Add(dataGridView1);
this.Load += new EventHandler(Form1_Load);
this.Text = "DataGridView validation demo (disallows empty CompanyName)";
}
<br /><span space="preserve">...</span><br /> [STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.Run(new Form1());
}
#using <System.dll>
#using <System.Data.dll>
#using <System.Windows.Forms.dll>
#using <System.Drawing.dll>
#using <System.Xml.dll>
#using <System.EnterpriseServices.dll>
#using <System.Transactions.dll>
http://msdn2.microsoft.com/en-us/library/ykdxa0bc(vs.80,d=printer).aspx 5/24/2007
Walkthrough: Validating Data in the Windows Forms DataGridView Control Page 3 of 7
public:
Form1()
{
dataGridView1 = gcnew DataGridView();
bindingSource1 = gcnew BindingSource();
// Initialize the form.
this->dataGridView1->Dock = DockStyle::Fill;
this->Controls->Add(dataGridView1);
this->Load += gcnew EventHandler(this, &Form1::Form1_Load);
}
<br /><span space="preserve">...</span><br />public:
[STAThread]
static void Main()
{
Application::EnableVisualStyles();
Application::Run(gcnew Form1());
}
};
int main()
{
Form1::Main();
}
2. Implement a method in your form's class definition for handling the details of connecting to the
database.
This code example uses a GetData method that returns a populated DataTable
[ http://msdn2.microsoft.com/en-us/library/system.data.datatable(VS.80).aspx ] object. Be sure
that you set the connectionString variable to a value that is appropriate for your database.
Security Note
Storing sensitive information, such as a password, within the connection string can affect
the security of your application. Using Windows Authentication, also known as integrated
security, is a more secure way to control access to a database. For more information, see
Securing Connection Strings [ http://msdn2.microsoft.com/en-us/library/89211k9b
(VS.80).aspx ] .
Return data
End Function
C# Copy Code
http://msdn2.microsoft.com/en-us/library/ykdxa0bc(vs.80,d=printer).aspx 5/24/2007
Walkthrough: Validating Data in the Windows Forms DataGridView Control Page 4 of 7
return data;
}
private:
DataTable^ GetData(String^ selectCommand)
{
String^ connectionString =
"Integrated Security=SSPI;Persist Security Info=False;" +
"Initial Catalog=Northwind;Data Source=localhost;Packet Size=4096";
return data;
}
End Sub
C# Copy Code
http://msdn2.microsoft.com/en-us/library/ykdxa0bc(vs.80,d=printer).aspx 5/24/2007
Walkthrough: Validating Data in the Windows Forms DataGridView Control Page 5 of 7
this.dataGridView1.CellEndEdit += new
DataGridViewCellEventHandler(dataGridView1_CellEndEdit);
private:
void Form1_Load(System::Object^ /*sender*/, System::EventArgs^ /*e*/)
{
// Attach DataGridView events to the corresponding event handlers.
this->dataGridView1->CellValidating += gcnew
DataGridViewCellValidatingEventHandler(this, &Form1::dataGridView1_CellVa
this->dataGridView1->CellEndEdit += gcnew
DataGridViewCellEventHandler(this, &Form1::dataGridView1_CellEndEdit);
http://msdn2.microsoft.com/en-us/library/ykdxa0bc(vs.80,d=printer).aspx 5/24/2007
Walkthrough: Validating Data in the Windows Forms DataGridView Control Page 6 of 7
End If
End Sub
' Clear the row error in case the user presses ESC.
dataGridView1.Rows(e.RowIndex).ErrorText = String.Empty
End Sub
C# Copy Code
private:
void dataGridView1_CellValidating(Object^ /*sender*/,
DataGridViewCellValidatingEventArgs^ e)
{
// Validate the CompanyName entry by disallowing empty strings.
if (dataGridView1->Columns[e->ColumnIndex]->Name == "CompanyName")
{
if (e->FormattedValue->ToString() == String::Empty)
{
dataGridView1->Rows[e->RowIndex]->ErrorText =
"Company Name must not be empty";
e->Cancel = true;
}
}
}
private:
void dataGridView1_CellEndEdit(Object^ /*sender*/, DataGridViewCellEventArgs^ e)
{
http://msdn2.microsoft.com/en-us/library/ykdxa0bc(vs.80,d=printer).aspx 5/24/2007
Walkthrough: Validating Data in the Windows Forms DataGridView Control Page 7 of 7
You will see a DataGridView filled with data from the Customers table. When you double-click a
cell in the CompanyName column, you can edit the value. If you delete all the characters and hit the
TAB key to exit the cell, the DataGridView prevents you from exiting. When you type a non-
empty string into the cell, the DataGridView control lets you exit the cell.
Next Steps
This application gives you a basic understanding of the DataGridView control's capabilities. You can
customize the appearance and behavior of the DataGridView control in several ways:
z Change border and header styles. For more information, see How to: Change the Border and
Gridline Styles in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/ehz9ksfa(VS.80).aspx ] .
z Enable or restrict user input to the DataGridView control. For more information, see How to:
Prevent Row Addition and Deletion in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/61bk13ye(VS.80).aspx ] , and How to: Make Columns
Read-Only in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/cze614bb(VS.80).aspx ] .
z Check user input for database-related errors. For more information, see Walkthrough: Handling
Errors that Occur During Data Entry in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/t4a23xx4(VS.80).aspx ] .
z Handle very large data sets using virtual mode. For more information, see Walkthrough:
Implementing Virtual Mode in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/15a31akc(VS.80).aspx ] .
z Customize the appearance of cells. For more information, see How to: Customize the Appearance
of Cells in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/hta8z9sz(VS.80).aspx ] and How to: Set Font and Color Styles in the Windows Forms
DataGridView Control [ http://msdn2.microsoft.com/en-us/library/z2akwyy7(VS.80).aspx ] .
See Also
Tasks
How to: Validate Data in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/7ehy30d4(VS.80).aspx ]
Walkthrough: Handling Errors that Occur During Data Entry in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/t4a23xx4(VS.80).aspx ]
Reference
DataGridView [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview
(VS.80).aspx ]
BindingSource [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.bindingsource
(VS.80).aspx ]
Concepts
Securing Connection Strings [ http://msdn2.microsoft.com/en-us/library/89211k9b(VS.80).aspx ]
Other Resources
Data Entry in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/ms171610(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/ykdxa0bc(vs.80,d=printer).aspx 5/24/2007
How to: Validate Data in the Windows Forms DataGridView Control Page 1 of 5
For a complete explanation of this code example, see Walkthrough: Validating Data in the Windows Forms
DataGridView Control [ http://msdn2.microsoft.com/en-us/library/ykdxa0bc(VS.80).aspx ] .
Example
Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.Windows.Forms
End Sub
End Sub
End Sub
http://msdn2.microsoft.com/en-us/library/7ehy30d4(vs.80,d=printer).aspx 5/24/2007
How to: Validate Data in the Windows Forms DataGridView Control Page 2 of 5
Handles dataGridView1.CellEndEdit
' Clear the row error in case the user presses ESC.
dataGridView1.Rows(e.RowIndex).ErrorText = String.Empty
End Sub
Return data
End Function
<STAThread()> _
Shared Sub Main()
Application.EnableVisualStyles()
Application.Run(New Form1())
End Sub
End Class
C# Copy Code
using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
public Form1()
{
// Initialize the form.
this.dataGridView1.Dock = DockStyle.Fill;
this.Controls.Add(dataGridView1);
this.Load += new EventHandler(Form1_Load);
this.Text = "DataGridView validation demo (disallows empty CompanyName)";
}
http://msdn2.microsoft.com/en-us/library/7ehy30d4(vs.80,d=printer).aspx 5/24/2007
How to: Validate Data in the Windows Forms DataGridView Control Page 3 of 5
return data;
}
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.Run(new Form1());
}
#using <System.dll>
#using <System.Data.dll>
#using <System.Windows.Forms.dll>
#using <System.Drawing.dll>
#using <System.Xml.dll>
#using <System.EnterpriseServices.dll>
#using <System.Transactions.dll>
public:
Form1()
{
dataGridView1 = gcnew DataGridView();
bindingSource1 = gcnew BindingSource();
// Initialize the form.
this->dataGridView1->Dock = DockStyle::Fill;
this->Controls->Add(dataGridView1);
this->Load += gcnew EventHandler(this, &Form1::Form1_Load);
}
private:
void Form1_Load(System::Object^ /*sender*/, System::EventArgs^ /*e*/)
{
// Attach DataGridView events to the corresponding event handlers.
this->dataGridView1->CellValidating += gcnew
DataGridViewCellValidatingEventHandler(this, &Form1::dataGridView1_CellValidati
this->dataGridView1->CellEndEdit += gcnew
DataGridViewCellEventHandler(this, &Form1::dataGridView1_CellEndEdit);
http://msdn2.microsoft.com/en-us/library/7ehy30d4(vs.80,d=printer).aspx 5/24/2007
How to: Validate Data in the Windows Forms DataGridView Control Page 4 of 5
private:
void dataGridView1_CellValidating(Object^ /*sender*/,
DataGridViewCellValidatingEventArgs^ e)
{
// Validate the CompanyName entry by disallowing empty strings.
if (dataGridView1->Columns[e->ColumnIndex]->Name == "CompanyName")
{
if (e->FormattedValue->ToString() == String::Empty)
{
dataGridView1->Rows[e->RowIndex]->ErrorText =
"Company Name must not be empty";
e->Cancel = true;
}
}
}
private:
void dataGridView1_CellEndEdit(Object^ /*sender*/, DataGridViewCellEventArgs^ e)
{
// Clear the row error in case the user presses ESC.
dataGridView1->Rows[e->RowIndex]->ErrorText = String::Empty;
}
private:
DataTable^ GetData(String^ selectCommand)
{
String^ connectionString =
"Integrated Security=SSPI;Persist Security Info=False;" +
"Initial Catalog=Northwind;Data Source=localhost;Packet Size=4096";
return data;
}
public:
[STAThread]
static void Main()
{
Application::EnableVisualStyles();
Application::Run(gcnew Form1());
}
};
int main()
{
Form1::Main();
}
For information about building this example from the command line for Visual Basic or Visual C#, see
Building from the Command Line (Visual Basic) [ http://msdn2.microsoft.com/en-us/library/25fz1td5
(VS.80).aspx ] or Command-Line Building [ http://msdn2.microsoft.com/en-us/library/78f4aasd
(VS.80).aspx ] . You can also build this example in Visual Studio by pasting the code into a new project.
For more information, see How to: Compile and Run a Complete Windows Forms Code Example Using
Visual Studio [ http://msdn2.microsoft.com/en-us/bb129228(vs.80).aspx ] and How to: Compile and
Run a Complete Windows Forms Code Example Using Visual Studio [ http://msdn2.microsoft.com/en-
us/bb129228(vs.90).aspx ] .
Security
Storing sensitive information, such as a password, within the connection string can affect the security of
your application. Using Windows Authentication (also known as integrated security) is a more secure way to
control access to a database. For more information, see Securing Connection Strings
http://msdn2.microsoft.com/en-us/library/7ehy30d4(vs.80,d=printer).aspx 5/24/2007
How to: Validate Data in the Windows Forms DataGridView Control Page 5 of 5
[ http://msdn2.microsoft.com/en-us/library/89211k9b(VS.80).aspx ] .
See Also
Tasks
Walkthrough: Validating Data in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/ykdxa0bc(VS.80).aspx ]
Walkthrough: Handling Errors that Occur During Data Entry in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/t4a23xx4(VS.80).aspx ]
Reference
DataGridView [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview
(VS.80).aspx ]
BindingSource [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.bindingsource
(VS.80).aspx ]
Concepts
Securing Connection Strings [ http://msdn2.microsoft.com/en-us/library/89211k9b(VS.80).aspx ]
Other Resources
Data Entry in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/ms171610(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/7ehy30d4(vs.80,d=printer).aspx 5/24/2007
Walkthrough: Handling Errors that Occur During Data Entry in the Windows Forms Data... Page 1 of 5
In this walkthrough, you will retrieve rows from the Customers table in the Northwind sample database and
display them in a DataGridView control. When a duplicate CustomerID value is detected in a new row or
an edited existing row, the DataError event will occur, which will be handled by displaying a MessageBox
[ http://msdn2.microsoft.com/en-us/library/system.windows.forms.messagebox(VS.80).aspx ] that
describes the exception.
To copy the code in this topic as a single listing, see How to: Handle Errors That Occur During Data Entry in
the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-us/library/xktax5sd
(VS.80).aspx ] .
Prerequisites
In order to complete this walkthrough, you will need:
z Access to a server that has the Northwind SQL Server sample database.
Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.Windows.Forms
End Sub
<br /><span space="preserve">...</span><br /> <STAThread()> _
http://msdn2.microsoft.com/en-us/library/t4a23xx4(vs.80,d=printer).aspx 5/24/2007
Walkthrough: Handling Errors that Occur During Data Entry in the Windows Forms Data... Page 2 of 5
End Class
C# Copy Code
using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
public Form1()
{
// Initialize the form.
this.dataGridView1.Dock = DockStyle.Fill;
this.Controls.Add(dataGridView1);
this.Load += new EventHandler(Form1_Load);
}
<br /><span space="preserve">...</span><br /> [STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.Run(new Form1());
}
2. Implement a method in your form's class definition for handling the details of connecting to the
database.
This code example uses a GetData method that returns a populated DataTable
[ http://msdn2.microsoft.com/en-us/library/system.data.datatable(VS.80).aspx ] object. Be sure
that you set the connectionString variable to a value that is appropriate for your database.
Security Note
Storing sensitive information, such as a password, within the connection string can affect
the security of your application. Using Windows Authentication (also known as integrated
security) is a more secure way to control access to a database. For more information, see
Securing Connection Strings [ http://msdn2.microsoft.com/en-us/library/89211k9b
(VS.80).aspx ] .
http://msdn2.microsoft.com/en-us/library/t4a23xx4(vs.80,d=printer).aspx 5/24/2007
Walkthrough: Handling Errors that Occur During Data Entry in the Windows Forms Data... Page 3 of 5
' Connect to the database and fill a data table, including the
' schema information that contains the CustomerID column
' constraint.
Dim adapter As New SqlDataAdapter(selectCommand, connectionString)
Dim data As New DataTable()
data.Locale = System.Globalization.CultureInfo.InvariantCulture
adapter.Fill(data)
adapter.FillSchema(data, SchemaType.Source)
Return data
End Function
C# Copy Code
return data;
}
End Sub
C# Copy Code
http://msdn2.microsoft.com/en-us/library/t4a23xx4(vs.80,d=printer).aspx 5/24/2007
Walkthrough: Handling Errors that Occur During Data Entry in the Windows Forms Data... Page 4 of 5
End If
End Sub
C# Copy Code
You will see a DataGridView control filled with data from the Customers table. If you enter a
duplicate value for CustomerID and commit the edit, the cell value will revert automatically and
you will see a MessageBox that displays the data entry error.
Next Steps
This application gives you a basic understanding of the DataGridView control's capabilities. You can
customize the appearance and behavior of the DataGridView control in several ways:
z Change border and header styles. For more information, see How to: Change the Border and
Gridline Styles in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/ehz9ksfa(VS.80).aspx ] .
http://msdn2.microsoft.com/en-us/library/t4a23xx4(vs.80,d=printer).aspx 5/24/2007
Walkthrough: Handling Errors that Occur During Data Entry in the Windows Forms Data... Page 5 of 5
z Enable or restrict user input to the DataGridView control. For more information, see How to:
Prevent Row Addition and Deletion in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/61bk13ye(VS.80).aspx ] , and How to: Make Columns
Read-Only in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/cze614bb(VS.80).aspx ] .
z Validate user input to the DataGridView control. For more information, see Walkthrough:
Validating Data in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/ykdxa0bc(VS.80).aspx ] .
z Handle very large data sets using virtual mode. For more information, see Walkthrough:
Implementing Virtual Mode in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/15a31akc(VS.80).aspx ] .
z Customize the appearance of cells. For more information, see How to: Customize the Appearance
of Cells in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/hta8z9sz(VS.80).aspx ] and How to: Set Default Cell Styles for the Windows Forms
DataGridView Control [ http://msdn2.microsoft.com/en-us/library/k4sab6f9(VS.80).aspx ] .
See Also
Tasks
How to: Handle Errors That Occur During Data Entry in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/xktax5sd(VS.80).aspx ]
Walkthrough: Validating Data in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/ykdxa0bc(VS.80).aspx ]
Reference
DataGridView [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview
(VS.80).aspx ]
BindingSource [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.bindingsource
(VS.80).aspx ]
Concepts
Securing Connection Strings [ http://msdn2.microsoft.com/en-us/library/89211k9b(VS.80).aspx ]
Other Resources
Data Entry in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/ms171610(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/t4a23xx4(vs.80,d=printer).aspx 5/24/2007
How to: Handle Errors That Occur During Data Entry in the Windows Forms DataGridVi... Page 1 of 3
For a complete explanation of this code example, see Walkthrough: Handling Errors that Occur During Data
Entry in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-us/library/t4a23xx4
(VS.80).aspx ] .
Example
Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.Windows.Forms
End Sub
End Sub
End If
End Sub
' Connect to the database and fill a data table, including the
' schema information that contains the CustomerID column
http://msdn2.microsoft.com/en-us/library/xktax5sd(vs.80,d=printer).aspx 5/24/2007
How to: Handle Errors That Occur During Data Entry in the Windows Forms DataGridVi... Page 2 of 3
' constraint.
Dim adapter As New SqlDataAdapter(selectCommand, connectionString)
Dim data As New DataTable()
data.Locale = System.Globalization.CultureInfo.InvariantCulture
adapter.Fill(data)
adapter.FillSchema(data, SchemaType.Source)
Return data
End Function
<STAThread()> _
Shared Sub Main()
Application.EnableVisualStyles()
Application.Run(New Form1())
End Sub
End Class
C# Copy Code
using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
public Form1()
{
// Initialize the form.
this.dataGridView1.Dock = DockStyle.Fill;
this.Controls.Add(dataGridView1);
this.Load += new EventHandler(Form1_Load);
}
http://msdn2.microsoft.com/en-us/library/xktax5sd(vs.80,d=printer).aspx 5/24/2007
How to: Handle Errors That Occur During Data Entry in the Windows Forms DataGridVi... Page 3 of 3
return data;
}
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.Run(new Form1());
}
For information about building this example from the command line for Visual Basic or Visual C#, see
Building from the Command Line (Visual Basic) [ http://msdn2.microsoft.com/en-us/library/25fz1td5
(VS.80).aspx ] or Command-Line Building [ http://msdn2.microsoft.com/en-us/library/78f4aasd
(VS.80).aspx ] . You can also build this example in Visual Studio by pasting the code into a new project.
For more information, see How to: Compile and Run a Complete Windows Forms Code Example Using
Visual Studio [ http://msdn2.microsoft.com/en-us/bb129228(vs.80).aspx ] and How to: Compile and
Run a Complete Windows Forms Code Example Using Visual Studio [ http://msdn2.microsoft.com/en-
us/bb129228(vs.90).aspx ] .
Security
Storing sensitive information, such as a password, within the connection string can affect the security of
your application. Using Windows Authentication (also known as integrated security) is a more secure way to
control access to a database. For more information, see Securing Connection Strings
[ http://msdn2.microsoft.com/en-us/library/89211k9b(VS.80).aspx ] .
See Also
Tasks
Walkthrough: Handling Errors that Occur During Data Entry in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/t4a23xx4(VS.80).aspx ]
Walkthrough: Validating Data in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/ykdxa0bc(VS.80).aspx ]
Reference
DataGridView [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview
(VS.80).aspx ]
BindingSource [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.bindingsource
(VS.80).aspx ]
Concepts
Securing Connection Strings [ http://msdn2.microsoft.com/en-us/library/89211k9b(VS.80).aspx ]
Other Resources
Data Entry in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/ms171610(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/xktax5sd(vs.80,d=printer).aspx 5/24/2007
Selection and Clipboard Use with the Windows Forms DataGridView Control Page 1 of 2
In This Section
How to: Set the Selection Mode of the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/wfc9h72k(VS.80).aspx ]
Describes how to configure the control for single-row selection when a user clicks a cell.
How to: Get the Selected Cells, Rows, and Columns in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/x8x9zk5a(VS.80).aspx ]
Describes how to work with the selected cell, row, and column collections.
How to: Enable Users to Copy Multiple Cells to the Clipboard from the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/dec5efh1(VS.80).aspx ]
Describes how to enable Clipboard support in the control.
Reference
DataGridView [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview
(VS.80).aspx ]
Provides reference documentation for the DataGridView control.
System.Windows.Forms.DataGridView.SelectionMode [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.selectionmode(VS.80).aspx ]
Provides reference documentation for the SelectionMode property.
ClipboardCopyMode [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.clipboardcopymode(VS.80).aspx ]
Provides reference documentation for the ClipboardCopyMode property.
DataGridViewSelectedCellCollection [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewselectedcellcollection(VS.80).aspx ]
Provides reference documentation for the DataGridViewSelectedCellCollection class.
DataGridViewSelectedRowCollection [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewselectedrowcollection(VS.80).aspx ]
Provides reference documentation for the DataGridViewSelectedRowCollection class.
DataGridViewSelectedColumnCollection [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewselectedcolumncollection(VS.80).aspx ]
Provides reference documentation for the DataGridViewSelectedColumnCollection class.
See Also
Reference
Default Keyboard and Mouse Handling in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/tb9t9a2t(VS.80).aspx ]
http://msdn2.microsoft.com/en-us/library/ms171614(vs.80,d=printer).aspx 5/24/2007
Selection and Clipboard Use with the Windows Forms DataGridView Control Page 2 of 2
Other Resources
DataGridView Control (Windows Forms) [ http://msdn2.microsoft.com/en-us/library/e0ywh3cz
(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/ms171614(vs.80,d=printer).aspx 5/24/2007
Selection Modes in the Windows Forms DataGridView Control Page 1 of 2
Note
Changing the selection mode at run time automatically clears the current selection.
By default, users can select multiple rows, columns, or cells by dragging with the mouse, pressing CTRL or
SHIFT while selecting to extend or modify a selection, or clicking the top-left header cell to select all cells in
the control. To prevent this behavior, set the MultiSelect [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.multiselect(VS.80).aspx ] property to false.
The FullRowSelect and RowHeaderSelect modes allow users to delete rows by selecting them and
pressing the DELETE key. Users can delete rows only when the current cell is not in edit mode, the
AllowUserToDeleteRows [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.allowusertodeleterows(VS.80).aspx ] property is set to true,
and the underlying data source supports user-driven row deletion. Note that these settings do not prevent
programmatic row deletion.
Programmatic Selection
The current selection mode restricts the behavior of programmatic selection as well as user selection. You
can change the current selection programmatically by setting the Selected property of any cells, rows, or
columns present in the DataGridView control. You can also select all cells in the control through the
SelectAll [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview.selectall
http://msdn2.microsoft.com/en-us/library/8x6w9028(vs.80,d=printer).aspx 5/24/2007
Selection Modes in the Windows Forms DataGridView Control Page 2 of 2
(VS.80).aspx ] method, depending on the selection mode. To clear the selection, use the ClearSelection
[ http://msdn2.microsoft.com/en-us/library/bxdf3ekh(VS.80).aspx ] method.
If the MultiSelect property is set to true, you can add DataGridView elements to or remove them from
the selection by changing the Selected property of the element. Otherwise, setting the Selected property
to true for one element automatically removes other elements from the selection.
You can retrieve a collection of the currently selected cells, rows, or columns through the SelectedCells
[ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview.selectedcells
(VS.80).aspx ] , SelectedRows [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.selectedrows(VS.80).aspx ] , and SelectedColumns
[ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview.selectedcolumns
(VS.80).aspx ] properties of the DataGridView control. Accessing these properties is inefficient when
every cell in the control is selected. To avoid a performance penalty in this case, use the AreAllCellsSelected
[ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview.areallcellsselected
(VS.80).aspx ] method first. Additionally, accessing these collections to determine the number of selected
cells, rows, or columns can be inefficient. Instead, you should use the GetCellCount
[ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview.getcellcount
(VS.80).aspx ] , GetRowCount [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewrowcollection.getrowcount(VS.80).aspx ] , or
GetColumnCount [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcolumncollection.getcolumncount(VS.80).aspx ] method,
passing in the Selected [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewelementstates(VS.80).aspx ] value.
See Also
Tasks
How to: Set the Selection Mode of the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/wfc9h72k(VS.80).aspx ]
Reference
DataGridView [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview
(VS.80).aspx ]
MultiSelect [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview.multiselect
(VS.80).aspx ]
SelectionMode [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.selectionmode(VS.80).aspx ]
DataGridViewSelectionMode [ http://msdn2.microsoft.com/en-us/library/3c89df86(VS.80).aspx ]
Other Resources
Selection and Clipboard Use with the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/ms171614(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/8x6w9028(vs.80,d=printer).aspx 5/24/2007
How to: Set the Selection Mode of the Windows Forms DataGridView Control Page 1 of 1
Example
With Me.dataGridView1
.SelectionMode = DataGridViewSelectionMode.FullRowSelect
.MultiSelect = False
End With
C# Copy Code
this.dataGridView1.SelectionMode =
DataGridViewSelectionMode.FullRowSelect;
this.dataGridView1.MultiSelect = false;
See Also
Reference
DataGridView [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview
(VS.80).aspx ]
MultiSelect [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview.multiselect
(VS.80).aspx ]
SelectionMode [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.selectionmode(VS.80).aspx ]
DataGridViewSelectionMode [ http://msdn2.microsoft.com/en-us/library/3c89df86(VS.80).aspx ]
Concepts
Selection Modes in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/8x6w9028(VS.80).aspx ]
Other Resources
Selection and Clipboard Use with the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/ms171614(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/wfc9h72k(vs.80,d=printer).aspx 5/24/2007
How to: Get the Selected Cells, Rows, and Columns in the Windows Forms DataGridVie... Page 1 of 4
Note
If dataGridView1.AreAllCellsSelected(True) Then
Else
Dim i As Integer
For i = 0 To selectedCellCount - 1
sb.Append("Row: ")
sb.Append(dataGridView1.SelectedCells(i).RowIndex _
.ToString())
sb.Append(", Column: ")
sb.Append(dataGridView1.SelectedCells(i).ColumnIndex _
.ToString())
sb.Append(Environment.NewLine)
Next i
End If
End If
End Sub
http://msdn2.microsoft.com/en-us/library/x8x9zk5a(vs.80,d=printer).aspx 5/24/2007
How to: Get the Selected Cells, Rows, and Columns in the Windows Forms DataGridVie... Page 2 of 4
C# Copy Code
for (int i = 0;
i < selectedCellCount; i++)
{
sb.Append("Row: ");
sb.Append(dataGridView1.SelectedCells[i].RowIndex
.ToString());
sb.Append(", Column: ");
sb.Append(dataGridView1.SelectedCells[i].ColumnIndex
.ToString());
sb.Append(Environment.NewLine);
}
z Use the SelectedRows property. To enable users to select rows, you must set the SelectionMode
[ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview.selectionmode
(VS.80).aspx ] property to FullRowSelect [ http://msdn2.microsoft.com/en-us/library/3c89df86
(VS.80).aspx ] or RowHeaderSelect [ http://msdn2.microsoft.com/en-us/library/3c89df86
(VS.80).aspx ] .
Dim i As Integer
For i = 0 To selectedRowCount - 1
sb.Append("Row: ")
sb.Append(dataGridView1.SelectedRows(i).Index.ToString())
sb.Append(Environment.NewLine)
Next i
End If
End Sub
C# Copy Code
http://msdn2.microsoft.com/en-us/library/x8x9zk5a(vs.80,d=printer).aspx 5/24/2007
How to: Get the Selected Cells, Rows, and Columns in the Windows Forms DataGridVie... Page 3 of 4
z Use the SelectedColumns property. To enable users to select columns, you must set the
SelectionMode property to FullColumnSelect [ http://msdn2.microsoft.com/en-us/library/3c89df86
(VS.80).aspx ] or ColumnHeaderSelect [ http://msdn2.microsoft.com/en-us/library/3c89df86
(VS.80).aspx ] .
Dim i As Integer
For i = 0 To selectedColumnCount - 1
sb.Append("Column: ")
sb.Append(dataGridView1.SelectedColumns(i).Index.ToString())
sb.Append(Environment.NewLine)
Next i
End If
End Sub
C# Copy Code
http://msdn2.microsoft.com/en-us/library/x8x9zk5a(vs.80,d=printer).aspx 5/24/2007
How to: Get the Selected Cells, Rows, and Columns in the Windows Forms DataGridVie... Page 4 of 4
z Button [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.button(VS.80).aspx ]
controls named selectedCellsButton, selectedRowsButton, and selectedColumnsButton, each
with handlers for the Click [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.control.click(VS.80).aspx ] event attached.
z A DataGridView control named dataGridView1.
Robust Programming
The collections described in this topic do not perform efficiently when large numbers of cells, rows, or
columns are selected. For more information about using these collections with large amounts of data,
see Best Practices for Scaling the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/ha5xt0d9(VS.80).aspx ] .
See Also
Reference
DataGridView [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview
(VS.80).aspx ]
SelectionMode [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.selectionmode(VS.80).aspx ]
AreAllCellsSelected [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.areallcellsselected(VS.80).aspx ]
SelectedCells [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview.selectedcells
(VS.80).aspx ]
SelectedRows [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.selectedrows(VS.80).aspx ]
SelectedColumns [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.selectedcolumns(VS.80).aspx ]
Other Resources
Selection and Clipboard Use with the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/ms171614(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/x8x9zk5a(vs.80,d=printer).aspx 5/24/2007
How to: Enable Users to Copy Multiple Cells to the Clipboard from the Windows Forms ... Page 1 of 4
You can configure cell copying to copy cell values only, to include row and column header text in the
Clipboard data, or to include header text only when users select entire rows or columns.
Depending on the selection mode, users can select multiple disconnected groups of cells. When a user
copies cells to the Clipboard, rows and columns with no selected cells are not copied. All other rows or
columns become rows and columns in the table of data copied to the Clipboard. Unselected cells in these
rows or columns are copied as blank placeholders to the Clipboard.
Me.DataGridView1.ClipboardCopyMode = _
DataGridViewClipboardCopyMode.EnableWithoutHeaderText
C# Copy Code
this.DataGridView1.ClipboardCopyMode =
DataGridViewClipboardCopyMode.EnableWithoutHeaderText;
Example
The following complete code example demonstrates how cells are copied to the Clipboard. This example
includes a button that copies the selected cells to the Clipboard using the
System.Windows.Forms.DataGridView.GetClipboardContent [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.getclipboardcontent(VS.80).aspx ] method and displays
the Clipboard contents in a text box.
Imports System
Imports System.Windows.Forms
<STAThreadAttribute()> _
Public Shared Sub Main()
Application.Run(New Form1())
End Sub
http://msdn2.microsoft.com/en-us/library/dec5efh1(vs.80,d=printer).aspx 5/24/2007
How to: Enable Users to Copy Multiple Cells to the Clipboard from the Windows Forms ... Page 2 of 4
Me.DataGridView1.AllowUserToAddRows = False
Me.DataGridView1.Dock = DockStyle.Fill
Me.Controls.Add(Me.DataGridView1)
Me.TextBox1.Multiline = True
Me.TextBox1.Height = 100
Me.TextBox1.Dock = DockStyle.Bottom
Me.Controls.Add(Me.TextBox1)
End Sub
End Sub
If Me.DataGridView1.GetCellCount( _
DataGridViewElementStates.Selected) > 0 Then
Try
' Replace the text box contents with the clipboard text.
Me.TextBox1.Text = Clipboard.GetText()
Catch ex As System.Runtime.InteropServices.ExternalException
Me.TextBox1.Text = _
"The Clipboard could not be accessed. Please try again."
End Try
End If
End Sub
End Class
C# Copy Code
using System;
using System.Windows.Forms;
[STAThreadAttribute()]
public static void Main()
{
Application.Run(new Form1());
}
public Form1()
{
this.DataGridView1.AllowUserToAddRows = false;
this.DataGridView1.Dock = DockStyle.Fill;
http://msdn2.microsoft.com/en-us/library/dec5efh1(vs.80,d=printer).aspx 5/24/2007
How to: Enable Users to Copy Multiple Cells to the Clipboard from the Windows Forms ... Page 3 of 4
this.Controls.Add(this.DataGridView1);
this.TextBox1.Multiline = true;
this.TextBox1.Height = 100;
this.TextBox1.Dock = DockStyle.Bottom;
this.Controls.Add(this.TextBox1);
For information about building this example from the command line for Visual Basic or Visual C#, see
Building from the Command Line (Visual Basic) [ http://msdn2.microsoft.com/en-us/library/25fz1td5
(VS.80).aspx ] or Command-Line Building [ http://msdn2.microsoft.com/en-us/library/78f4aasd
(VS.80).aspx ] . You can also build this example in Visual Studio by pasting the code into a new project.
For more information, see How to: Compile and Run a Complete Windows Forms Code Example Using
Visual Studio [ http://msdn2.microsoft.com/en-us/bb129228(vs.80).aspx ] and How to: Compile and
Run a Complete Windows Forms Code Example Using Visual Studio [ http://msdn2.microsoft.com/en-
us/bb129228(vs.90).aspx ] .
See Also
Reference
DataGridView [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview
(VS.80).aspx ]
http://msdn2.microsoft.com/en-us/library/dec5efh1(vs.80,d=printer).aspx 5/24/2007
How to: Enable Users to Copy Multiple Cells to the Clipboard from the Windows Forms ... Page 4 of 4
ClipboardCopyMode [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.clipboardcopymode(VS.80).aspx ]
GetClipboardContent [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.getclipboardcontent(VS.80).aspx ]
Other Resources
Selection and Clipboard Use with the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/ms171614(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/dec5efh1(vs.80,d=printer).aspx 5/24/2007
Programming with Cells, Rows, and Columns in the Windows Forms DataGridView Con... Page 1 of 2
In This Section
How to: Add ToolTips to Individual Cells in a Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/2249cf0a(VS.80).aspx ]
Describes how to handle the CellFormatting [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.cellformatting(VS.80).aspx ] event to provide
different ToolTips for individual cells.
How to: Perform a Custom Action Based on Changes in a Cell of a Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/ewk0cc1s(VS.80).aspx ]
Describes how to handle the CellValueChanged [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.cellvaluechanged(VS.80).aspx ] and
CellStateChanged [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.cellstatechanged(VS.80).aspx ] events.
How to: Manipulate Bands in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/2346by52(VS.80).aspx ]
Describes how to program with objects of type DataGridViewBand [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewband(VS.80).aspx ] , which is the base type for rows
and columns.
How to: Manipulate Rows in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/ddtce152(VS.80).aspx ]
Describes how to program with objects of type DataGridViewRow.
How to: Work with Image Columns in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/x0tz73t0(VS.80).aspx ]
Describes how to program with the DataGridViewImageColumn class.
Reference
DataGridView [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview
(VS.80).aspx ]
Provides reference documentation for the DataGridView control.
DataGridViewCell [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridviewcell
(VS.80).aspx ]
Provides reference documentation for the DataGridViewCell class.
DataGridViewRow [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridviewrow
(VS.80).aspx ]
Provides reference documentation for the DataGridViewRow class.
DataGridViewColumn [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcolumn(VS.80).aspx ]
Provides reference documentation for the DataGridViewColumn class.
Related Sections
http://msdn2.microsoft.com/en-us/library/ms171616(vs.80,d=printer).aspx 5/24/2007
Programming with Cells, Rows, and Columns in the Windows Forms DataGridView Con... Page 2 of 2
Basic Column, Row, and Cell Features in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/ms171596(VS.80).aspx ]
Provides topics that describe commonly used cell, row, and column properties.
See Also
Concepts
Column Types in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/bxt3k60s(VS.80).aspx ]
Other Resources
DataGridView Control (Windows Forms) [ http://msdn2.microsoft.com/en-us/library/e0ywh3cz
(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/ms171616(vs.80,d=printer).aspx 5/24/2007
How to: Add ToolTips to Individual Cells in a Windows Forms DataGridView Control Page 1 of 3
You can also disable the display of cell-level ToolTips by setting the
System.Windows.Forms.DataGridView.ShowCellToolTips [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.showcelltooltips(VS.80).aspx ] property to false.
' Sets the ToolTip text for cells in the Rating column.
Sub dataGridView1_CellFormatting(ByVal sender As Object, _
ByVal e As DataGridViewCellFormattingEventArgs) _
Handles dataGridView1.CellFormatting
If e.ColumnIndex = Me.dataGridView1.Columns("Rating").Index _
AndAlso (e.Value IsNot Nothing) Then
With Me.dataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex)
If e.Value.Equals("*") Then
.ToolTipText = "very bad"
ElseIf e.Value.Equals("**") Then
.ToolTipText = "bad"
ElseIf e.Value.Equals("***") Then
.ToolTipText = "good"
ElseIf e.Value.Equals("****") Then
.ToolTipText = "very good"
End If
End With
End If
C# Copy Code
http://msdn2.microsoft.com/en-us/library/2249cf0a(vs.80,d=printer).aspx 5/24/2007
How to: Add ToolTips to Individual Cells in a Windows Forms DataGridView Control Page 2 of 3
}
else if (e.Value.Equals("***"))
{
cell.ToolTipText = "good";
}
else if (e.Value.Equals("****"))
{
cell.ToolTipText = "very good";
}
}
}
Robust Programming
When you bind the DataGridView control to an external data source or provide your own data source
by implementing virtual mode, you might encounter performance issues. To avoid a performance
penalty when working with large amounts of data, handle the CellToolTipTextNeeded
[ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview.celltooltiptextneeded
(VS.80).aspx ] event rather than setting the ToolTipText property of multiple cells. When you handle
this event, getting the value of a cell ToolTipText property raises the event and returns the value of
the System.Windows.Forms.DataGridViewCellToolTipTextNeededEventArgs.ToolTipText
[ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcelltooltiptextneededeventargs.tooltiptext(VS.80).aspx ]
property as specified in the event handler.
See Also
http://msdn2.microsoft.com/en-us/library/2249cf0a(vs.80,d=printer).aspx 5/24/2007
How to: Add ToolTips to Individual Cells in a Windows Forms DataGridView Control Page 3 of 3
Reference
DataGridView [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview
(VS.80).aspx ]
System.Windows.Forms.DataGridView.ShowCellToolTips [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.showcelltooltips(VS.80).aspx ]
System.Windows.Forms.DataGridView.CellToolTipTextNeeded [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.celltooltiptextneeded(VS.80).aspx ]
DataGridViewCell [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridviewcell
(VS.80).aspx ]
System.Windows.Forms.DataGridViewCell.ToolTipText [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcell.tooltiptext(VS.80).aspx ]
Other Resources
Programming with Cells, Rows, and Columns in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/ms171616(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/2249cf0a(vs.80,d=printer).aspx 5/24/2007
How to: Perform a Custom Action Based on Changes in a Cell of a Windows Forms Data... Page 1 of 2
End Sub
C# Copy Code
End Sub
C# Copy Code
http://msdn2.microsoft.com/en-us/library/ewk0cc1s(vs.80,d=printer).aspx 5/24/2007
How to: Perform a Custom Action Based on Changes in a Cell of a Windows Forms Data... Page 2 of 2
{
DataGridViewElementStates state = e.StateChanged;
string msg = String.Format("Row {0}, Column {1}, {2}",
e.Cell.RowIndex, e.Cell.ColumnIndex, e.StateChanged);
MessageBox.Show(msg, "Cell State Changed");
}
z A DataGridView control named dataGridView1. For C#, the event handlers must be connected to
the corresponding events.
z References to the System [ http://msdn2.microsoft.com/en-us/library/system(VS.80).aspx ] and
System.Windows.Forms [ http://msdn2.microsoft.com/en-us/library/system.windows.forms
(VS.80).aspx ] assemblies.
See Also
Tasks
Walkthrough: Validating Data in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/ykdxa0bc(VS.80).aspx ]
Reference
DataGridView [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview
(VS.80).aspx ]
System.Windows.Forms.DataGridView.CellValueChanged [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.cellvaluechanged(VS.80).aspx ]
System.Windows.Forms.DataGridView.CellStateChanged [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.cellstatechanged(VS.80).aspx ]
Other Resources
Programming with Cells, Rows, and Columns in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/ms171616(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/ewk0cc1s(vs.80,d=printer).aspx 5/24/2007
How to: Manipulate Bands in the Windows Forms DataGridView Control Page 1 of 8
Example
Imports System.Windows.Forms
Imports System.Drawing
AddButton(Button1, "Reset")
AddButton(Button2, "Change Column 3 Header")
AddButton(Button3, "Change Meatloaf Recipe")
AddAdditionalButtons()
End Sub
http://msdn2.microsoft.com/en-us/library/2346by52(vs.80,d=printer).aspx 5/24/2007
How to: Manipulate Bands in the Windows Forms DataGridView Control Page 2 of 8
PostRowCreation()
shortMode = False
boringRecipe = True
End Sub
FlowLayoutPanel1.Controls.Add(button)
button.TabIndex = FlowLayoutPanel1.Controls.Count
button.Text = buttonLabel
button.AutoSize = True
End Sub
http://msdn2.microsoft.com/en-us/library/2346by52(vs.80,d=printer).aspx 5/24/2007
How to: Manipulate Bands in the Windows Forms DataGridView Control Page 3 of 8
Toggle(shortMode)
If shortMode Then dataGridView.Columns(2).HeaderText = _
"S" _
Else dataGridView.Columns(2).HeaderText = _
thirdColumnHeader
End Sub
Toggle(boringRecipe)
If boringRecipe Then
SetMeatloaf(boringMeatloaf, boringMeatloafRanking)
Else
Dim greatMeatloafRecipe As String = "1 lb. lean ground beef, " _
& "1/2 cup bread crumbs, 1/4 cup ketchup," _
& "1/3 tsp onion powder, " _
& "1 clove of garlic, 1/2 pack onion soup mix " _
& " dash of your favorite BBQ Sauce"
SetMeatloaf(greatMeatloafRecipe, "***")
End If
End Sub
dataGridView.Rows(0).Cells(2).Value = recipe
dataGridView.Rows(0).Cells(3).Value = rating
End Sub
#End Region
FreezeBand(dataGridView.Rows(0))
End Sub
FreezeBand(dataGridView.Columns(1))
End Sub
band.Frozen = True
Dim style As DataGridViewCellStyle = New DataGridViewCellStyle()
style.BackColor = Color.WhiteSmoke
band.DefaultCellStyle = style
End Sub
http://msdn2.microsoft.com/en-us/library/2346by52(vs.80,d=printer).aspx 5/24/2007
How to: Manipulate Bands in the Windows Forms DataGridView Control Page 4 of 8
<STAThreadAttribute()> _
Public Shared Sub Main()
Application.Run(New DataGridViewBandDemo())
End Sub
End Class
C# Copy Code
using System.Drawing;
using System.Windows.Forms;
using System;
AddButton(Button1, "Reset",
new EventHandler(Button1_Click));
AddButton(Button2, "Change Column 3 Header",
new EventHandler(Button2_Click));
AddButton(Button3, "Change Meatloaf Recipe",
new EventHandler(Button3_Click));
AddAdditionalButtons();
InitializeDataGridView();
http://msdn2.microsoft.com/en-us/library/2346by52(vs.80,d=printer).aspx 5/24/2007
How to: Manipulate Bands in the Windows Forms DataGridView Control Page 5 of 8
DataGridView dataGridView;
Button Button1 = new Button();
Button Button2 = new Button();
Button Button3 = new Button();
Button Button4 = new Button();
Button Button5 = new Button();
Button Button6 = new Button();
Button Button7 = new Button();
Button Button8 = new Button();
Button Button9 = new Button();
Button Button10 = new Button();
FlowLayoutPanel FlowLayoutPanel1 = new FlowLayoutPanel();
http://msdn2.microsoft.com/en-us/library/2346by52(vs.80,d=printer).aspx 5/24/2007
How to: Manipulate Bands in the Windows Forms DataGridView Control Page 6 of 8
PostRowCreation();
shortMode = false;
boringRecipe = true;
}
http://msdn2.microsoft.com/en-us/library/2346by52(vs.80,d=printer).aspx 5/24/2007
How to: Manipulate Bands in the Windows Forms DataGridView Control Page 7 of 8
FreezeBand(dataGridView.Rows[0]);
}
FreezeBand(dataGridView.Columns[1]);
}
http://msdn2.microsoft.com/en-us/library/2346by52(vs.80,d=printer).aspx 5/24/2007
How to: Manipulate Bands in the Windows Forms DataGridView Control Page 8 of 8
}
}
[STAThreadAttribute()]
public static void Main()
{
Application.Run(new DataGridViewBandDemo());
}
}
For information about building this example from the command line for Visual Basic or Visual C#, see
Building from the Command Line (Visual Basic) [ http://msdn2.microsoft.com/en-us/library/25fz1td5
(VS.80).aspx ] or Command-Line Building [ http://msdn2.microsoft.com/en-us/library/78f4aasd
(VS.80).aspx ] . You can also build this example in Visual Studio by pasting the code into a new project.
For more information, see How to: Compile and Run a Complete Windows Forms Code Example Using
Visual Studio [ http://msdn2.microsoft.com/en-us/bb129228(vs.80).aspx ] and How to: Compile and
Run a Complete Windows Forms Code Example Using Visual Studio [ http://msdn2.microsoft.com/en-
us/bb129228(vs.90).aspx ] .
See Also
Reference
DataGridView [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview
(VS.80).aspx ]
DataGridViewBand [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridviewband
(VS.80).aspx ]
DataGridViewRow [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridviewrow
(VS.80).aspx ]
DataGridViewColumn [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcolumn(VS.80).aspx ]
Other Resources
Programming with Cells, Rows, and Columns in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/ms171616(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/2346by52(vs.80,d=printer).aspx 5/24/2007
How to: Manipulate Rows in the Windows Forms DataGridView Control Page 1 of 8
Example
Imports System.Windows.Forms
Imports System.Drawing
AddButton(Button1, "Reset")
AddButton(Button2, "Change Column 3 Header")
AddButton(Button3, "Change Meatloaf Recipe")
AddAdditionalButtons()
End Sub
http://msdn2.microsoft.com/en-us/library/ddtce152(vs.80,d=printer).aspx 5/24/2007
How to: Manipulate Rows in the Windows Forms DataGridView Control Page 2 of 8
shortMode = False
boringRecipe = True
End Sub
FlowLayoutPanel1.Controls.Add(button)
button.TabIndex = FlowLayoutPanel1.Controls.Count
button.Text = buttonLabel
button.AutoSize = True
End Sub
Toggle(shortMode)
If shortMode Then dataGridView.Columns(2).HeaderText = _
"S" _
http://msdn2.microsoft.com/en-us/library/ddtce152(vs.80,d=printer).aspx 5/24/2007
How to: Manipulate Rows in the Windows Forms DataGridView Control Page 3 of 8
Else dataGridView.Columns(2).HeaderText = _
thirdColumnHeader
End Sub
Toggle(boringRecipe)
If boringRecipe Then
SetMeatloaf(boringMeatloaf, boringMeatloafRanking)
Else
Dim greatMeatloafRecipe As String = "1 lb. lean ground beef, " _
& "1/2 cup bread crumbs, 1/4 cup ketchup," _
& "1/3 tsp onion powder, " _
& "1 clove of garlic, 1/2 pack onion soup mix " _
& " dash of your favorite BBQ Sauce"
SetMeatloaf(greatMeatloafRecipe, "***")
End If
End Sub
dataGridView.Rows(0).Cells(2).Value = recipe
dataGridView.Rows(0).Cells(3).Value = rating
End Sub
#End Region
http://msdn2.microsoft.com/en-us/library/ddtce152(vs.80,d=printer).aspx 5/24/2007
How to: Manipulate Rows in the Windows Forms DataGridView Control Page 4 of 8
End Sub
UpdateStars(dataGridView.Rows(4), "******************")
End Sub
row.Cells(ratingColumn).Value = stars
' Resize the column width to account for the new value.
row.DataGridView.AutoResizeColumn(ratingColumn, _
DataGridViewAutoSizeColumnMode.DisplayedCells)
End Sub
#End Region
<STAThreadAttribute()> _
Public Shared Sub Main()
Application.Run(New DataGridViewRowDemo())
End Sub
End Class
C# Copy Code
using System.Windows.Forms;
using System;
using System.Drawing;
AddButton(Button1, "Reset",
new EventHandler(Button1_Click));
AddButton(Button2, "Change Column 3 Header",
new EventHandler(Button2_Click));
AddButton(Button3, "Change Meatloaf Recipe",
new EventHandler(Button3_Click));
AddAdditionalButtons();
InitializeDataGridView();
}
http://msdn2.microsoft.com/en-us/library/ddtce152(vs.80,d=printer).aspx 5/24/2007
How to: Manipulate Rows in the Windows Forms DataGridView Control Page 5 of 8
shortMode = false;
boringRecipe = true;
}
http://msdn2.microsoft.com/en-us/library/ddtce152(vs.80,d=printer).aspx 5/24/2007
How to: Manipulate Rows in the Windows Forms DataGridView Control Page 6 of 8
InitializeDataGridView();
}
int secondRow = 1;
DataGridViewRow row = dataGridView.Rows[secondRow];
row.MinimumHeight = 40;
}
// Set height.
private void Button5_Click(object sender, System.EventArgs e)
{
http://msdn2.microsoft.com/en-us/library/ddtce152(vs.80,d=printer).aspx 5/24/2007
How to: Manipulate Rows in the Windows Forms DataGridView Control Page 7 of 8
int rowNumber = 1;
foreach (DataGridViewRow row in dataGridView.Rows)
{
if (row.IsNewRow) continue;
row.HeaderCell.Value = "Row " + rowNumber;
rowNumber = rowNumber + 1;
}
dataGridView.AutoResizeRowHeadersWidth(
DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders);
}
int ratingColumn = 3;
row.Cells[ratingColumn].Value = stars;
[STAThreadAttribute()]
public static void Main()
{
Application.Run(new DataGridViewRowDemo());
}
}
For information about building this example from the command line for Visual Basic or Visual C#, see
Building from the Command Line (Visual Basic) [ http://msdn2.microsoft.com/en-us/library/25fz1td5
(VS.80).aspx ] or Command-Line Building [ http://msdn2.microsoft.com/en-us/library/78f4aasd
(VS.80).aspx ] . You can also build this example in Visual Studio by pasting the code into a new project.
For more information, see How to: Compile and Run a Complete Windows Forms Code Example Using
Visual Studio [ http://msdn2.microsoft.com/en-us/bb129228(vs.80).aspx ] and How to: Compile and
Run a Complete Windows Forms Code Example Using Visual Studio [ http://msdn2.microsoft.com/en-
us/bb129228(vs.90).aspx ] .
See Also
Reference
DataGridView [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview
http://msdn2.microsoft.com/en-us/library/ddtce152(vs.80,d=printer).aspx 5/24/2007
How to: Manipulate Rows in the Windows Forms DataGridView Control Page 8 of 8
(VS.80).aspx ]
DataGridViewBand [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridviewband
(VS.80).aspx ]
DataGridViewRow [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridviewrow
(VS.80).aspx ]
DataGridViewColumn [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcolumn(VS.80).aspx ]
Other Resources
Programming with Cells, Rows, and Columns in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/ms171616(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/ddtce152(vs.80,d=printer).aspx 5/24/2007
How to: Manipulate Columns in the Windows Forms DataGridView Control Page 1 of 11
Example
Imports System.Windows.Forms
Imports System.Drawing
AddButton(Button1, "Reset")
AddButton(Button2, "Change Column 3 Header")
AddButton(Button3, "Change Meatloaf Recipe")
AddAdditionalButtons()
End Sub
http://msdn2.microsoft.com/en-us/library/wc06dx4f(vs.80,d=printer).aspx 5/24/2007
How to: Manipulate Columns in the Windows Forms DataGridView Control Page 2 of 11
PostColumnCreation()
shortMode = False
boringRecipe = True
End Sub
FlowLayoutPanel1.Controls.Add(button)
button.TabIndex = FlowLayoutPanel1.Controls.Count
button.Text = buttonLabel
button.AutoSize = True
End Sub
Toggle(shortMode)
If shortMode Then dataGridView.Columns(2).HeaderText = _
"S" _
Else dataGridView.Columns(2).HeaderText = _
thirdColumnHeader
http://msdn2.microsoft.com/en-us/library/wc06dx4f(vs.80,d=printer).aspx 5/24/2007
How to: Manipulate Columns in the Windows Forms DataGridView Control Page 3 of 11
End Sub
Toggle(boringRecipe)
If boringRecipe Then
SetMeatloaf(boringMeatloaf, boringMeatloafRanking)
Else
Dim greatMeatloafRecipe As String = "1 lb. lean ground beef, " _
& "1/2 cup bread crumbs, 1/4 cup ketchup," _
& "1/3 tsp onion powder, " _
& "1 clove of garlic, 1/2 pack onion soup mix " _
& " dash of your favorite BBQ Sauce"
SetMeatloaf(greatMeatloafRecipe, "***")
End If
End Sub
dataGridView.Rows(0).Cells(2).Value = recipe
dataGridView.Rows(0).Cells(3).Value = rating
End Sub
#End Region
cell.Style.BackColor = Color.Wheat
http://msdn2.microsoft.com/en-us/library/wc06dx4f(vs.80,d=printer).aspx 5/24/2007
How to: Manipulate Columns in the Windows Forms DataGridView Control Page 4 of 11
column.CellTemplate = cell
End Sub
column.ContextMenuStrip = strip
column.ContextMenuStrip.Items.Add(toolStripItem1)
Next
End Sub
' Change the cell's color.
Private Sub toolStripItem1_Click(ByVal sender As Object, _
ByVal args As EventArgs) _
Handles toolStripItem1.Click
dataGridView.Rows(mouseLocation.RowIndex) _
.Cells(mouseLocation.ColumnIndex) _
.Style.BackColor = Color.Red
End Sub
mouseLocation = location
End Sub
firstColumn.DefaultCellStyle = cellStyle
End Sub
http://msdn2.microsoft.com/en-us/library/wc06dx4f(vs.80,d=printer).aspx 5/24/2007
How to: Manipulate Columns in the Windows Forms DataGridView Control Page 5 of 11
End Sub
column.HeaderCell.Value = _
column.Index.ToString
column.HeaderCell.Style = style
Next
End Sub
http://msdn2.microsoft.com/en-us/library/wc06dx4f(vs.80,d=printer).aspx 5/24/2007
How to: Manipulate Columns in the Windows Forms DataGridView Control Page 6 of 11
Handles DataGridView.AutoSizeColumnModeChanged
args.Column.DataGridView.Parent. _
Controls("flowlayoutpanel"). _
Controls(criteriaLabel).Text = _
criteriaLabel & args.Column.AutoSizeMode.ToString
End Sub
#End Region
<STAThreadAttribute()> _
Public Shared Sub Main()
Application.Run(New DataGridViewColumnDemo())
End Sub
End Class
C# Copy Code
using System.Windows.Forms;
using System;
using System.Drawing;
AddButton(Button1, "Reset",
new EventHandler(ResetToDisorder));
AddButton(Button2, "Change Column 3 Header",
new EventHandler(ChangeColumn3Header));
AddButton(Button3, "Change Meatloaf Recipe",
new EventHandler(ChangeMeatloafRecipe));
AddAdditionalButtons();
InitializeDataGridView();
}
DataGridView dataGridView;
Button Button1 = new Button();
Button Button2 = new Button();
Button Button3 = new Button();
Button Button4 = new Button();
Button Button5 = new Button();
Button Button6 = new Button();
Button Button7 = new Button();
Button Button8 = new Button();
Button Button9 = new Button();
Button Button10 = new Button();
FlowLayoutPanel FlowLayoutPanel1 = new FlowLayoutPanel();
http://msdn2.microsoft.com/en-us/library/wc06dx4f(vs.80,d=printer).aspx 5/24/2007
How to: Manipulate Columns in the Windows Forms DataGridView Control Page 7 of 11
PostColumnCreation();
shortMode = false;
boringRecipe = true;
}
http://msdn2.microsoft.com/en-us/library/wc06dx4f(vs.80,d=printer).aspx 5/24/2007
How to: Manipulate Columns in the Windows Forms DataGridView Control Page 8 of 11
Toggle(ref boringRecipe);
if (boringRecipe)
{
SetMeatloaf(boringMeatloaf, boringMeatloafRanking);
}
else
{
string greatMeatloafRecipe =
"1 lb. lean ground beef, " +
"1/2 cup bread crumbs, 1/4 cup ketchup," +
"1/3 tsp onion powder, " +
"1 clove of garlic, 1/2 pack onion soup mix " +
" dash of your favorite BBQ Sauce";
SetMeatloaf(greatMeatloafRecipe, "***");
}
}
dataGridView.CellMouseEnter +=
dataGridView_CellMouseEnter;
dataGridView.AutoSizeColumnModeChanged +=
dataGridView_AutoSizeColumnModeChanged;
}
http://msdn2.microsoft.com/en-us/library/wc06dx4f(vs.80,d=printer).aspx 5/24/2007
How to: Manipulate Columns in the Windows Forms DataGridView Control Page 9 of 11
cell.Style.BackColor = Color.Wheat;
column.CellTemplate = cell;
}
column.ContextMenuStrip = strip;
column.ContextMenuStrip.Items.Add(toolStripItem1);
}
}
firstColumn.DefaultCellStyle = cellStyle;
}
http://msdn2.microsoft.com/en-us/library/wc06dx4f(vs.80,d=printer).aspx 5/24/2007
How to: Manipulate Columns in the Windows Forms DataGridView Control Page 10 of 11
DataGridViewColumn firstVisibleColumn =
columnCollection.GetFirstColumn(DataGridViewElementStates.Visible);
DataGridViewColumn lastVisibleColumn =
columnCollection.GetLastColumn(
DataGridViewElementStates.Visible, DataGridViewElementStates.None);
http://msdn2.microsoft.com/en-us/library/wc06dx4f(vs.80,d=printer).aspx 5/24/2007
How to: Manipulate Columns in the Windows Forms DataGridView Control Page 11 of 11
[STAThreadAttribute()]
public static void Main()
{
Application.Run(new DataGridViewColumnDemo());
}
For information about building this example from the command line for Visual Basic or Visual C#, see
Building from the Command Line (Visual Basic) [ http://msdn2.microsoft.com/en-us/library/25fz1td5
(VS.80).aspx ] or Command-Line Building [ http://msdn2.microsoft.com/en-us/library/78f4aasd
(VS.80).aspx ] . You can also build this example in Visual Studio by pasting the code into a new project.
For more information, see How to: Compile and Run a Complete Windows Forms Code Example Using
Visual Studio [ http://msdn2.microsoft.com/en-us/bb129228(vs.80).aspx ] and How to: Compile and
Run a Complete Windows Forms Code Example Using Visual Studio [ http://msdn2.microsoft.com/en-
us/bb129228(vs.90).aspx ] .
See Also
Reference
DataGridView [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview
(VS.80).aspx ]
DataGridViewBand [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridviewband
(VS.80).aspx ]
DataGridViewRow [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridviewrow
(VS.80).aspx ]
DataGridViewColumn [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcolumn(VS.80).aspx ]
Other Resources
Programming with Cells, Rows, and Columns in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/ms171616(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/wc06dx4f(vs.80,d=printer).aspx 5/24/2007
How to: Work with Image Columns in the Windows Forms DataGridView Control Page 1 of 11
Example
Imports System.IO
Imports System.Windows.Forms
Imports System.Drawing
Imports System
#Region "bitmaps"
Private oImage As Byte() = { _
&H42, &H4D, &HC6, &H0, &H0, &H0, &H0, &H0, _
&H0, &H0, &H76, &H0, &H0, &H0, &H28, &H0, _
&H0, &H0, &HB, &H0, &H0, &H0, &HA, &H0, _
&H0, &H0, &H1, &H0, &H4, &H0, &H0, &H0, _
&H0, &H0, &H50, &H0, &H0, &H0, &H0, &H0, _
&H0, &H0, &H0, &H0, &H0, &H0, &H10, &H0, _
&H0, &H0, &H10, &H0, &H0, &H0, &H0, &H0, _
&H0, &H0, &H0, &H0, &H80, &H0, &H0, &H80, _
&H0, &H0, &H0, &H80, &H80, &H0, &H80, &H0, _
&H0, &H0, &H80, &H0, &H80, &H0, &H80, &H80, _
&H0, &H0, &HC0, &HC0, &HC0, &H0, &H80, &H80, _
&H80, &H0, &H0, &H0, &HFF, &H0, &H0, &HFF, _
&H0, &H0, &H0, &HFF, &HFF, &H0, &HFF, &H0, _
&H0, &H0, &HFF, &H0, &HFF, &H0, &HFF, &HFF, _
&H0, &H0, &HFF, &HFF, &HFF, &H0, &HFF, &HFF, _
&H0, &HF, &HFF, &HF0, &H0, &H0, &HFF, &H0, _
&HFF, &HF0, &HF, &HF0, &H0, &H0, &HF0, &HFF, _
&HFF, &HFF, &HF0, &HF0, &H0, &H0, &HF0, &HFF, _
&HFF, &HFF, &HF0, &HF0, &H0, &H0, &HF, &HFF, _
&HFF, &HFF, &HFF, &H0, &H0, &H0, &HF, &HFF, _
&HFF, &HFF, &HFF, &H0, &H0, &H0, &HF0, &HFF, _
&HFF, &HFF, &HF0, &HF0, &H0, &H0, &HF0, &HFF, _
&HFF, &HFF, &HF0, &HF0, &H0, &H0, &HFF, &H0, _
&HFF, &HF0, &HF, &HF0, &H0, &H0, &HFF, &HFF, _
&H0, &HF, &HFF, &HF0, &H0, &H0}
http://msdn2.microsoft.com/en-us/library/x0tz73t0(vs.80,d=printer).aspx 5/24/2007
How to: Work with Image Columns in the Windows Forms DataGridView Control Page 2 of 11
ConfigureForm()
SizeGrid()
CreateColumns()
CreateRows()
ResumeLayout(False)
Panel1.ResumeLayout(False)
End Sub
Panel1.FlowDirection = FlowDirection.TopDown
Panel1.Location = New System.Drawing.Point(0, 8)
Panel1.Size = New System.Drawing.Size(120, 196)
http://msdn2.microsoft.com/en-us/library/x0tz73t0(vs.80,d=printer).aspx 5/24/2007
How to: Work with Image Columns in the Windows Forms DataGridView Control Page 3 of 11
Panel1.Controls.Add(button)
button.Text = buttonLabel
button.AutoSize = True
End Sub
imageColumn.Image = unMarked
imageColumn.ImageLayout = DataGridViewImageCellLayout.NotSet
imageColumn.Description = "default image layout"
dataGridView1.Columns.Add(imageColumn)
columnCount = columnCount + 1
Loop While columnCount < 3
End Sub
' Add twice the padding for the top and bottom of the cell.
dataGridView1.RowTemplate.Height = x.Height + _
2 * bitmapPadding + 1
dataGridView1.AutoSize = True
End Sub
dataGridView1.Dispose()
InitializeDataGridView(Nothing, Nothing)
End Sub
http://msdn2.microsoft.com/en-us/library/x0tz73t0(vs.80,d=printer).aspx 5/24/2007
How to: Work with Image Columns in the Windows Forms DataGridView Control Page 4 of 11
CType(dataGridView1.Rows(e.RowIndex). _
Cells(e.ColumnIndex), DataGridViewImageCell)
If (cell.Value Is blank) Then
If IsOsTurn() Then
cell.Value = o
Else
cell.Value = x
End If
ToggleTurn()
ToolTip(e)
End If
If IsAWin() Then
turn.Text = gameOverString
End If
End Sub
cell.ToolTipText = imageColumn.Description
End Sub
dataGridView1.Cursor = Cursors.Default
End Sub
http://msdn2.microsoft.com/en-us/library/x0tz73t0(vs.80,d=printer).aspx 5/24/2007
How to: Work with Image Columns in the Windows Forms DataGridView Control Page 5 of 11
http://msdn2.microsoft.com/en-us/library/x0tz73t0(vs.80,d=printer).aspx 5/24/2007
How to: Work with Image Columns in the Windows Forms DataGridView Control Page 6 of 11
End Function
End Class
C# Copy Code
using System.IO;
using System.Windows.Forms;
using System.Drawing;
using System;
this.AutoSize = true;
SetupButtons();
InitializeDataGridView(null, null);
}
#region "bitmaps"
private byte[] oImage = new byte[] {
0x42, 0x4D, 0xC6, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x76,
0x0, 0x0, 0x0, 0x28, 0x0, 0x0, 0x0, 0xB, 0x0, 0x0, 0x0, 0xA,
0x0, 0x0, 0x0, 0x1, 0x0, 0x4, 0x0, 0x0, 0x0, 0x0, 0x0, 0x50,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x10,
0x0, 0x0, 0x0, 0x10, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x80, 0x0, 0x0, 0x80, 0x0, 0x0, 0x0, 0x80, 0x80, 0x0,
0x80, 0x0, 0x0, 0x0, 0x80, 0x0, 0x80, 0x0, 0x80, 0x80, 0x0,
0x0, 0xC0, 0xC0, 0xC0, 0x0, 0x80, 0x80, 0x80, 0x0, 0x0, 0x0,
0xFF, 0x0, 0x0, 0xFF, 0x0, 0x0, 0x0, 0xFF, 0xFF, 0x0, 0xFF,
0x0, 0x0, 0x0, 0xFF, 0x0, 0xFF, 0x0, 0xFF, 0xFF, 0x0, 0x0,
0xFF, 0xFF, 0xFF, 0x0, 0xFF, 0xFF, 0x0, 0xF, 0xFF, 0xF0,
0x0, 0x0, 0xFF, 0x0, 0xFF, 0xF0, 0xF, 0xF0, 0x0, 0x0, 0xF0,
0xFF, 0xFF, 0xFF, 0xF0, 0xF0, 0x0, 0x0, 0xF0, 0xFF, 0xFF,
0xFF, 0xF0, 0xF0, 0x0, 0x0, 0xF, 0xFF, 0xFF, 0xFF, 0xFF,
0x0, 0x0, 0x0, 0xF, 0xFF, 0xFF, 0xFF, 0xFF, 0x0, 0x0, 0x0,
0xF0, 0xFF, 0xFF, 0xFF, 0xF0, 0xF0, 0x0, 0x0, 0xF0, 0xFF,
0xFF, 0xFF, 0xF0, 0xF0, 0x0, 0x0, 0xFF, 0x0, 0xFF, 0xF0,
0xF, 0xF0, 0x0, 0x0, 0xFF, 0xFF, 0x0, 0xF, 0xFF, 0xF0, 0x0,
0x0};
http://msdn2.microsoft.com/en-us/library/x0tz73t0(vs.80,d=printer).aspx 5/24/2007
How to: Work with Image Columns in the Windows Forms DataGridView Control Page 7 of 11
0xFF, 0x0, 0xFF, 0xFF, 0x0, 0x0, 0xFF, 0xFF, 0xFF, 0x0,
0xF0, 0xFF, 0xFF, 0xFF, 0xF0, 0xF0, 0x0, 0x0, 0xFF, 0xF,
0xFF, 0xFF, 0xF, 0xF0, 0x0, 0x0, 0xFF, 0xF0, 0xFF, 0xF0,
0xFF, 0xF0, 0x0, 0x0, 0xFF, 0xFF, 0xF, 0xF, 0xFF, 0xF0, 0x0,
0x0, 0xFF, 0xFF, 0xF, 0xF, 0xFF, 0xF0, 0x0, 0x0, 0xFF, 0xFF,
0xF, 0xF, 0xFF, 0xF0, 0x0, 0x0, 0xFF, 0xF0, 0xFF, 0xF0,
0xFF, 0xF0, 0x0, 0x0, 0xFF, 0xF, 0xFF, 0xFF, 0xF, 0xF0, 0x0,
0x0, 0xF0, 0xFF, 0xFF, 0xFF, 0xF0, 0xF0, 0x0, 0x0, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xF0, 0x0, 0x0};
ConfigureForm();
SizeGrid();
CreateColumns();
CreateRows();
this.Panel1.ResumeLayout(false);
this.ResumeLayout(false);
}
Controls.Add(dataGridView1);
http://msdn2.microsoft.com/en-us/library/x0tz73t0(vs.80,d=printer).aspx 5/24/2007
How to: Work with Image Columns in the Windows Forms DataGridView Control Page 8 of 11
imageColumn.Image = unMarked;
dataGridView1.Columns.Add(imageColumn);
columnCount = columnCount + 1;
}
while (columnCount < 3);
}
dataGridView1.AutoSize = true;
}
if (turn.Text.Equals(gameOverString)) { return; }
if (cell.Value == blank)
{
http://msdn2.microsoft.com/en-us/library/x0tz73t0(vs.80,d=printer).aspx 5/24/2007
How to: Work with Image Columns in the Windows Forms DataGridView Control Page 9 of 11
if (IsOsTurn())
{
cell.Value = o;
}
else
{
cell.Value = x;
}
ToggleTurn();
}
if (IsAWin())
{
turn.Text = gameOverString;
}
}
if (markingUnderMouse == blank)
{
dataGridView1.Cursor = Cursors.Default;
}
else if (markingUnderMouse == o || markingUnderMouse == x)
{
dataGridView1.Cursor = Cursors.No;
ToolTip(e, true);
}
}
http://msdn2.microsoft.com/en-us/library/x0tz73t0(vs.80,d=printer).aspx 5/24/2007
How to: Work with Image Columns in the Windows Forms DataGridView Control Page 10 of 11
column.ImageLayout = DataGridViewImageCellLayout.Normal;
column.Description = "Normal";
}
}
http://msdn2.microsoft.com/en-us/library/x0tz73t0(vs.80,d=printer).aspx 5/24/2007
How to: Work with Image Columns in the Windows Forms DataGridView Control Page 11 of 11
return false;
}
[STAThread]
public static void Main()
{
Application.Run(new TicTacToe());
}
For information about building this example from the command line for Visual Basic or Visual C#, see
Building from the Command Line (Visual Basic) [ http://msdn2.microsoft.com/en-us/library/25fz1td5
(VS.80).aspx ] or Command-Line Building [ http://msdn2.microsoft.com/en-us/library/78f4aasd
(VS.80).aspx ] . You can also build this example in Visual Studio by pasting the code into a new project.
For more information, see How to: Compile and Run a Complete Windows Forms Code Example Using
Visual Studio [ http://msdn2.microsoft.com/en-us/bb129228(vs.80).aspx ] and How to: Compile and
Run a Complete Windows Forms Code Example Using Visual Studio [ http://msdn2.microsoft.com/en-
us/bb129228(vs.90).aspx ] .
See Also
Tasks
How to: Display Images in Cells of the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/2ab8kd75(VS.80).aspx ]
Reference
DataGridView [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview
(VS.80).aspx ]
DataGridViewImageColumn [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewimagecolumn(VS.80).aspx ]
Other Resources
Programming with Cells, Rows, and Columns in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/ms171616(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/x0tz73t0(vs.80,d=printer).aspx 5/24/2007
Customizing the Windows Forms DataGridView Control Page 1 of 2
To paint cells and rows yourself, you can handle various DataGridView painting events. To modify existing
functionality or provide new functionality, you can create your own types derived from the existing
DataGridViewCell, DataGridViewColumn, and DataGridViewRow types. You can also provide new
editing capabilities by creating derived types that display a control of your choosing when a cell is in edit
mode.
In This Section
How to: Customize the Appearance of Cells in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/hta8z9sz(VS.80).aspx ]
Describes how to handle the CellPainting [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.cellpainting(VS.80).aspx ] event in order to paint
cells manually.
How to: Customize the Appearance of Rows in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/85kxk29c(VS.80).aspx ]
Describes how to handle the RowPrePaint [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.rowprepaint(VS.80).aspx ] and RowPostPaint
[ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview.rowpostpaint
(VS.80).aspx ] events in order to paint rows with a custom, gradient background and content that
spans multiple columns.
How to: Customize Cells and Columns in the Windows Forms DataGridView Control by Extending Their
Behavior and Appearance [ http://msdn2.microsoft.com/en-us/library/7fb61s43(VS.80).aspx ]
Describes how to create custom types derived from DataGridViewCell and DataGridViewColumn
in order to highlight cells when the mouse pointer rests on them.
How to: Disable Buttons in a Button Column in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/ms171619(VS.80).aspx ]
Describes how to create custom types derived from DataGridViewButtonCell
[ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridviewbuttoncell
(VS.80).aspx ] and DataGridViewButtonColumn [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewbuttoncolumn(VS.80).aspx ] in order to display
disabled buttons in a button column.
Reference
DataGridView [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview
(VS.80).aspx ]
Provides reference documentation for the DataGridView control.
DataGridViewCell [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridviewcell
(VS.80).aspx ]
Provides reference documentation for the DataGridViewCell class.
http://msdn2.microsoft.com/en-us/library/ms171618(vs.80,d=printer).aspx 5/24/2007
Customizing the Windows Forms DataGridView Control Page 2 of 2
DataGridViewRow [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridviewrow
(VS.80).aspx ]
Provides reference documentation for the DataGridViewRow class.
DataGridViewColumn [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcolumn(VS.80).aspx ]
Provides reference documentation for the DataGridViewColumn class.
IDataGridViewEditingControl [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.idatagridvieweditingcontrol(VS.80).aspx ]
Provides reference documentation for the IDataGridViewEditingControl interface.
Related Sections
See Also
Concepts
Column Types in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/bxt3k60s(VS.80).aspx ]
Other Resources
DataGridView Control (Windows Forms) [ http://msdn2.microsoft.com/en-us/library/e0ywh3cz
(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/ms171618(vs.80,d=printer).aspx 5/24/2007
How to: Customize the Appearance of Cells in the Windows Forms DataGridView Control Page 1 of 3
In the following code example, you will paint all the cells in a ContactName column using the
DataGridView control's color scheme. Each cell's text content is painted in Crimson
[ http://msdn2.microsoft.com/en-us/library/system.drawing.color.crimson(VS.80).aspx ] , and an inset
rectangle is drawn in the same color as the DataGridView control's GridColor
[ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview.gridcolor(VS.80).aspx ]
property.
Example
If Me.dataGridView1.Columns("ContactName").Index = _
e.ColumnIndex AndAlso e.RowIndex >= 0 Then
Try
' Draw the grid lines (only the right and bottom lines;
' DataGridView takes care of the others).
e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left, _
e.CellBounds.Bottom - 1, e.CellBounds.Right - 1, _
e.CellBounds.Bottom - 1)
e.Graphics.DrawLine(gridLinePen, e.CellBounds.Right - 1, _
e.CellBounds.Top, e.CellBounds.Right - 1, _
e.CellBounds.Bottom)
http://msdn2.microsoft.com/en-us/library/hta8z9sz(vs.80,d=printer).aspx 5/24/2007
How to: Customize the Appearance of Cells in the Windows Forms DataGridView Control Page 2 of 3
End If
e.Handled = True
Finally
gridLinePen.Dispose()
gridBrush.Dispose()
backColorBrush.Dispose()
End Try
End If
End Sub
C# Copy Code
using (
Brush gridBrush = new SolidBrush(this.dataGridView1.GridColor),
backColorBrush = new SolidBrush(e.CellStyle.BackColor))
{
using (Pen gridLinePen = new Pen(gridBrush))
{
// Erase the cell.
e.Graphics.FillRectangle(backColorBrush, e.CellBounds);
// Draw the grid lines (only the right and bottom lines;
// DataGridView takes care of the others).
e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left,
e.CellBounds.Bottom - 1, e.CellBounds.Right - 1,
e.CellBounds.Bottom - 1);
e.Graphics.DrawLine(gridLinePen, e.CellBounds.Right - 1,
e.CellBounds.Top, e.CellBounds.Right - 1,
e.CellBounds.Bottom);
z A DataGridView control named dataGridView1 with a ContactName column such as the one in
the Customers table in the Northwind sample database.
z References to the System, System.Windows.Forms, and System.Drawing assemblies.
See Also
Reference
DataGridView [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview
(VS.80).aspx ]
CellPainting [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview.cellpainting
http://msdn2.microsoft.com/en-us/library/hta8z9sz(vs.80,d=printer).aspx 5/24/2007
How to: Customize the Appearance of Cells in the Windows Forms DataGridView Control Page 3 of 3
(VS.80).aspx ]
Other Resources
Customizing the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/ms171618(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/hta8z9sz(vs.80,d=printer).aspx 5/24/2007
How to: Customize the Appearance of Rows in the Windows Forms DataGridView Control Page 1 of 7
The following code example implements handlers for both events in order to provide a gradient selection
background and some custom foreground content that spans multiple columns.
Example
Imports System
Imports System.Drawing
Imports System.Windows.Forms
Class DataGridViewRowPainting
Inherits Form
Private WithEvents dataGridView1 As New DataGridView()
Private oldRowIndex As Int32 = 0
Private Const CUSTOM_CONTENT_HEIGHT As Int32 = 30
<STAThreadAttribute()> _
Public Shared Sub Main()
Application.Run(New DataGridViewRowPainting())
Me.dataGridView1.Dock = DockStyle.Fill
Me.Controls.Add(Me.dataGridView1)
Me.Text = "DataGridView row painting demo"
' Set a cell padding to provide space for the top of the focus
' rectangle and for the content that spans multiple columns.
Dim newPadding As New Padding(0, 1, 0, CUSTOM_CONTENT_HEIGHT)
Me.dataGridView1.RowTemplate.DefaultCellStyle.Padding = newPadding
' Set the row height to accommodate the normal cell content and the
' content that spans multiple columns.
Me.dataGridView1.RowTemplate.Height += CUSTOM_CONTENT_HEIGHT
http://msdn2.microsoft.com/en-us/library/85kxk29c(vs.80,d=printer).aspx 5/24/2007
How to: Customize the Appearance of Rows in the Windows Forms DataGridView Control Page 2 of 7
' Hide the column that contains the content that spans
' multiple columns.
Me.dataGridView1.Columns(2).Visible = False
' Adjust the row heights to accommodate the normal cell content.
Me.dataGridView1.AutoResizeRows( _
DataGridViewAutoSizeRowsMode.AllCellsExceptHeaders)
End Sub 'DataGridViewRowPainting_Load
Me.dataGridView1.Invalidate()
' Forces the row to repaint itself when the user changes the
' current cell. This is necessary to refresh the focus rectangle.
Sub dataGridView1_CurrentCellChanged(ByVal sender As Object, _
ByVal e As EventArgs) Handles dataGridView1.CurrentCellChanged
http://msdn2.microsoft.com/en-us/library/85kxk29c(vs.80,d=printer).aspx 5/24/2007
How to: Customize the Appearance of Rows in the Windows Forms DataGridView Control Page 3 of 7
' Paints the content that spans multiple columns and the focus rectangle.
Sub dataGridView1_RowPostPaint(ByVal sender As Object, _
ByVal e As DataGridViewRowPostPaintEventArgs) _
Handles dataGridView1.RowPostPaint
' Calculate the bounds for the content that spans multiple
' columns, adjusting for the horizontal scrolling position
' and the current row height, and displaying only whole
' lines of text.
Dim textArea As Rectangle = rowBounds
textArea.X -= Me.dataGridView1.HorizontalScrollingOffset
textArea.Width += Me.dataGridView1.HorizontalScrollingOffset
textArea.Y += rowBounds.Height - e.InheritedRowStyle.Padding.Bottom
textArea.Height -= rowBounds.Height - e.InheritedRowStyle.Padding.Bottom
textArea.Height = (textArea.Height \ e.InheritedRowStyle.Font.Height) * _
e.InheritedRowStyle.Font.Height
' Calculate the portion of the text area that needs painting.
Dim clip As RectangleF = textArea
clip.Width -= Me.dataGridView1.RowHeadersWidth + 1 - clip.X
clip.X = Me.dataGridView1.RowHeadersWidth + 1
Dim oldClip As RectangleF = e.Graphics.ClipBounds
e.Graphics.SetClip(clip)
e.Graphics.SetClip(oldClip)
End If
Finally
forebrush.Dispose()
End Try
http://msdn2.microsoft.com/en-us/library/85kxk29c(vs.80,d=printer).aspx 5/24/2007
How to: Customize the Appearance of Rows in the Windows Forms DataGridView Control Page 4 of 7
' Adjusts the padding when the user changes the row height so that
' the normal cell content is fully displayed and any extra
' height is used for the content that spans multiple columns.
Sub dataGridView1_RowHeightChanged(ByVal sender As Object, _
ByVal e As DataGridViewRowEventArgs) _
Handles dataGridView1.RowHeightChanged
End Sub
C# Copy Code
using System;
using System.Drawing;
using System.Windows.Forms;
[STAThreadAttribute()]
public static void Main()
{
Application.Run(new DataGridViewRowPainting());
}
public DataGridViewRowPainting()
{
this.dataGridView1.Dock = DockStyle.Fill;
this.Controls.Add(this.dataGridView1);
this.Load += new EventHandler(DataGridViewRowPainting_Load);
this.Text = "DataGridView row painting demo";
}
http://msdn2.microsoft.com/en-us/library/85kxk29c(vs.80,d=printer).aspx 5/24/2007
How to: Customize the Appearance of Rows in the Windows Forms DataGridView Control Page 5 of 7
this.dataGridView1.Columns[0].SortMode =
DataGridViewColumnSortMode.NotSortable;
this.dataGridView1.Columns[1].Name = "Category";
this.dataGridView1.Columns[2].Name = "Main Ingredients";
this.dataGridView1.Columns[3].Name = "Rating";
// Forces the row to repaint itself when the user changes the
// current cell. This is necessary to refresh the focus rectangle.
void dataGridView1_CurrentCellChanged(object sender, EventArgs e)
{
if (oldRowIndex != -1)
{
this.dataGridView1.InvalidateRow(oldRowIndex);
}
oldRowIndex = this.dataGridView1.CurrentCellAddress.Y;
}
http://msdn2.microsoft.com/en-us/library/85kxk29c(vs.80,d=printer).aspx 5/24/2007
How to: Customize the Appearance of Rows in the Windows Forms DataGridView Control Page 6 of 7
// Paints the content that spans multiple columns and the focus rectangle.
void dataGridView1_RowPostPaint(object sender,
DataGridViewRowPostPaintEventArgs e)
{
// Calculate the bounds of the row.
Rectangle rowBounds = new Rectangle(
this.dataGridView1.RowHeadersWidth, e.RowBounds.Top,
this.dataGridView1.Columns.GetColumnsWidth(
DataGridViewElementStates.Visible) -
this.dataGridView1.HorizontalScrollingOffset + 1,
e.RowBounds.Height);
if (recipe != null)
{
String text = recipe.ToString();
e.Graphics.SetClip(oldClip);
}
}
finally
http://msdn2.microsoft.com/en-us/library/85kxk29c(vs.80,d=printer).aspx 5/24/2007
How to: Customize the Appearance of Rows in the Windows Forms DataGridView Control Page 7 of 7
{
forebrush.Dispose();
}
if (this.dataGridView1.CurrentCellAddress.Y == e.RowIndex)
{
// Paint the focus rectangle.
e.DrawFocus(rowBounds, true);
}
}
// Adjusts the padding when the user changes the row height so that
// the normal cell content is fully displayed and any extra
// height is used for the content that spans multiple columns.
void dataGridView1_RowHeightChanged(object sender,
DataGridViewRowEventArgs e)
{
// Calculate the new height of the normal cell content.
Int32 preferredNormalContentHeight =
e.Row.GetPreferredHeight(e.Row.Index,
DataGridViewAutoSizeRowMode.AllCellsExceptHeader, true) -
e.Row.DefaultCellStyle.Padding.Bottom;
For information about building this example from the command line for Visual Basic or Visual C#, see
Building from the Command Line (Visual Basic) [ http://msdn2.microsoft.com/en-us/library/25fz1td5
(VS.80).aspx ] or Command-Line Building [ http://msdn2.microsoft.com/en-us/library/78f4aasd
(VS.80).aspx ] . You can also build this example in Visual Studio by pasting the code into a new project.
For more information, see How to: Compile and Run a Complete Windows Forms Code Example Using
Visual Studio [ http://msdn2.microsoft.com/en-us/bb129228(vs.80).aspx ] and How to: Compile and
Run a Complete Windows Forms Code Example Using Visual Studio [ http://msdn2.microsoft.com/en-
us/bb129228(vs.90).aspx ] .
See Also
Reference
DataGridView [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview
(VS.80).aspx ]
System.Windows.Forms.DataGridView.RowPrePaint [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.rowprepaint(VS.80).aspx ]
System.Windows.Forms.DataGridView.RowPostPaint [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.rowpostpaint(VS.80).aspx ]
Concepts
DataGridView Control Architecture (Windows Forms) [ http://msdn2.microsoft.com/en-us/library/dkdz8z4e
(VS.80).aspx ]
Other Resources
Customizing the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/ms171618(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/85kxk29c(vs.80,d=printer).aspx 5/24/2007
How to: Customize Cells and Columns in the Windows Forms DataGridView Control by ... Page 1 of 7
You create a custom DataGridViewCell class by deriving from the DataGridViewCell base class or one of
its derived classes. Although you can display any type of cell in any type of column, you will typically also
create a custom DataGridViewColumn [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcolumn(VS.80).aspx ] class specialized for displaying your
cell type. Column classes derive from DataGridViewColumn or one of its derived types.
In the following code example, you will create a custom cell class called DataGridViewRolloverCell that
detects when the mouse enters and leaves the cell boundaries. While the mouse is within the cell's bounds,
an inset rectangle is drawn. This new type derives from DataGridViewTextBoxCell
[ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridviewtextboxcell(VS.80).aspx ]
and behaves in all other respects as its base class. The companion column class is called
DataGridViewRolloverColumn.
To use these classes, create a form containing a DataGridView control, add one or more
DataGridViewRolloverColumn objects to the Columns [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.columns(VS.80).aspx ] collection, and populate the control
with rows containing values.
Note
This example will not work correctly if you add empty rows. Empty rows are created, for example,
when you add rows to the control by setting the RowCount [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.rowcount(VS.80).aspx ] property. This is because the
rows added in this case are automatically shared, which means that DataGridViewRolloverCell
objects are not instantiated until you click on individual cells, thereby causing the associated rows to
become unshared.
Because this type of cell customization requires unshared rows, it is not appropriate for use with large data
sets. For more information about row sharing, see Best Practices for Scaling the Windows Forms
DataGridView Control [ http://msdn2.microsoft.com/en-us/library/ha5xt0d9(VS.80).aspx ] .
Note
When you derive from DataGridViewCell or DataGridViewColumn and add new properties to the
derived class, be sure to override the Clone method to copy the new properties during cloning
operations. You should also call the base class's Clone method so that the properties of the base class
are copied to the new cell or column.
http://msdn2.microsoft.com/en-us/library/7fb61s43(vs.80,d=printer).aspx 5/24/2007
How to: Customize Cells and Columns in the Windows Forms DataGridView Control by ... Page 2 of 7
Inherits DataGridViewTextBoxCell
<br /><span space="preserve">...</span><br />End Class
C# Copy Code
' Call the base class method to paint the default cell appearance.
MyBase.Paint(graphics, clipBounds, cellBounds, rowIndex, elementState, _
value, formattedValue, errorText, cellStyle, _
advancedBorderStyle, paintParts)
' If the mouse pointer is over the current cell, draw a custom border.
If cellBounds.Contains(cursorPosition) Then
Dim newRect As New Rectangle(cellBounds.X + 1, _
cellBounds.Y + 1, cellBounds.Width - 4, _
cellBounds.Height - 4)
graphics.DrawRectangle(Pens.Red, newRect)
End If
End Sub
C# Copy Code
http://msdn2.microsoft.com/en-us/library/7fb61s43(vs.80,d=printer).aspx 5/24/2007
How to: Customize Cells and Columns in the Windows Forms DataGridView Control by ... Page 3 of 7
int rowIndex,
DataGridViewElementStates cellState,
object value,
object formattedValue,
string errorText,
DataGridViewCellStyle cellStyle,
DataGridViewAdvancedBorderStyle advancedBorderStyle,
DataGridViewPaintParts paintParts)
{
// Call the base class method to paint the default cell appearance.
base.Paint(graphics, clipBounds, cellBounds, rowIndex, cellState,
value, formattedValue, errorText, cellStyle,
advancedBorderStyle, paintParts);
// If the mouse pointer is over the current cell, draw a custom border.
if (cellBounds.Contains(cursorPosition))
{
Rectangle newRect = new Rectangle(cellBounds.X + 1,
cellBounds.Y + 1, cellBounds.Width - 4,
cellBounds.Height - 4);
graphics.DrawRectangle(Pens.Red, newRect);
}
}
' Force the cell to repaint itself when the mouse pointer enters it.
Protected Overrides Sub OnMouseEnter(ByVal rowIndex As Integer)
Me.DataGridView.InvalidateCell(Me)
End Sub
' Force the cell to repaint itself when the mouse pointer leaves it.
Protected Overrides Sub OnMouseLeave(ByVal rowIndex As Integer)
Me.DataGridView.InvalidateCell(Me)
End Sub
C# Copy Code
// Force the cell to repaint itself when the mouse pointer enters it.
protected override void OnMouseEnter(int rowIndex)
{
this.DataGridView.InvalidateCell(this);
}
// Force the cell to repaint itself when the mouse pointer leaves it.
protected override void OnMouseLeave(int rowIndex)
{
this.DataGridView.InvalidateCell(this);
http://msdn2.microsoft.com/en-us/library/7fb61s43(vs.80,d=printer).aspx 5/24/2007
How to: Customize Cells and Columns in the Windows Forms DataGridView Control by ... Page 4 of 7
End Class
C# Copy Code
Example
The complete code example includes a small test form that demonstrates the behavior of the custom
cell type.
Imports System
Imports System.Drawing
Imports System.Windows.Forms
Class Form1
Inherits Form
<STAThreadAttribute()> _
Public Shared Sub Main()
Application.Run(New Form1())
End Sub
End Class
http://msdn2.microsoft.com/en-us/library/7fb61s43(vs.80,d=printer).aspx 5/24/2007
How to: Customize Cells and Columns in the Windows Forms DataGridView Control by ... Page 5 of 7
' Call the base class method to paint the default cell appearance.
MyBase.Paint(graphics, clipBounds, cellBounds, rowIndex, elementState, _
value, formattedValue, errorText, cellStyle, _
advancedBorderStyle, paintParts)
' If the mouse pointer is over the current cell, draw a custom border.
If cellBounds.Contains(cursorPosition) Then
Dim newRect As New Rectangle(cellBounds.X + 1, _
cellBounds.Y + 1, cellBounds.Width - 4, _
cellBounds.Height - 4)
graphics.DrawRectangle(Pens.Red, newRect)
End If
End Sub
' Force the cell to repaint itself when the mouse pointer enters it.
Protected Overrides Sub OnMouseEnter(ByVal rowIndex As Integer)
Me.DataGridView.InvalidateCell(Me)
End Sub
' Force the cell to repaint itself when the mouse pointer leaves it.
Protected Overrides Sub OnMouseLeave(ByVal rowIndex As Integer)
Me.DataGridView.InvalidateCell(Me)
End Sub
End Class
End Class
C# Copy Code
using System;
using System.Drawing;
using System.Windows.Forms;
public Form1()
{
DataGridView dataGridView1 = new DataGridView();
DataGridViewRolloverCellColumn col =
new DataGridViewRolloverCellColumn();
dataGridView1.Columns.Add(col);
dataGridView1.Rows.Add(new string[] { "" });
dataGridView1.Rows.Add(new string[] { "" });
dataGridView1.Rows.Add(new string[] { "" });
dataGridView1.Rows.Add(new string[] { "" });
this.Controls.Add(dataGridView1);
this.Text = "DataGridView rollover-cell demo";
}
}
http://msdn2.microsoft.com/en-us/library/7fb61s43(vs.80,d=printer).aspx 5/24/2007
How to: Customize Cells and Columns in the Windows Forms DataGridView Control by ... Page 6 of 7
{
protected override void Paint(
Graphics graphics,
Rectangle clipBounds,
Rectangle cellBounds,
int rowIndex,
DataGridViewElementStates cellState,
object value,
object formattedValue,
string errorText,
DataGridViewCellStyle cellStyle,
DataGridViewAdvancedBorderStyle advancedBorderStyle,
DataGridViewPaintParts paintParts)
{
// Call the base class method to paint the default cell appearance.
base.Paint(graphics, clipBounds, cellBounds, rowIndex, cellState,
value, formattedValue, errorText, cellStyle,
advancedBorderStyle, paintParts);
// If the mouse pointer is over the current cell, draw a custom border.
if (cellBounds.Contains(cursorPosition))
{
Rectangle newRect = new Rectangle(cellBounds.X + 1,
cellBounds.Y + 1, cellBounds.Width - 4,
cellBounds.Height - 4);
graphics.DrawRectangle(Pens.Red, newRect);
}
}
// Force the cell to repaint itself when the mouse pointer enters it.
protected override void OnMouseEnter(int rowIndex)
{
this.DataGridView.InvalidateCell(this);
}
// Force the cell to repaint itself when the mouse pointer leaves it.
protected override void OnMouseLeave(int rowIndex)
{
this.DataGridView.InvalidateCell(this);
}
For information about building this example from the command line for Visual Basic or Visual C#, see
Building from the Command Line (Visual Basic) [ http://msdn2.microsoft.com/en-us/library/25fz1td5
(VS.80).aspx ] or Command-Line Building [ http://msdn2.microsoft.com/en-us/library/78f4aasd
(VS.80).aspx ] . You can also build this example in Visual Studio by pasting the code into a new project.
For more information, see How to: Compile and Run a Complete Windows Forms Code Example Using
Visual Studio [ http://msdn2.microsoft.com/en-us/bb129228(vs.80).aspx ] and How to: Compile and
Run a Complete Windows Forms Code Example Using Visual Studio [ http://msdn2.microsoft.com/en-
us/bb129228(vs.90).aspx ] .
See Also
Reference
DataGridView [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview
http://msdn2.microsoft.com/en-us/library/7fb61s43(vs.80,d=printer).aspx 5/24/2007
How to: Customize Cells and Columns in the Windows Forms DataGridView Control by ... Page 7 of 7
(VS.80).aspx ]
DataGridViewCell [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridviewcell
(VS.80).aspx ]
DataGridViewColumn [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcolumn(VS.80).aspx ]
Concepts
DataGridView Control Architecture (Windows Forms) [ http://msdn2.microsoft.com/en-us/library/dkdz8z4e
(VS.80).aspx ]
Column Types in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/bxt3k60s(VS.80).aspx ]
Best Practices for Scaling the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/ha5xt0d9(VS.80).aspx ]
Other Resources
Customizing the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/ms171618(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/7fb61s43(vs.80,d=printer).aspx 5/24/2007
How to: Disable Buttons in a Button Column in the Windows Forms DataGridView Cont... Page 1 of 7
The following code example demonstrates how to customize the DataGridViewButtonCell class to display
buttons that can appear disabled. The example defines a new cell type, DataGridViewDisableButtonCell,
that derives from DataGridViewButtonCell. This cell type provides a new Enabled property that can be
set to false to draw a disabled button in the cell. The example also defines a new column type,
DataGridViewDisableButtonColumn, that displays DataGridViewDisableButtonCell objects. To
demonstrate this new cell and column type, the current value of each DataGridViewCheckBoxCell
[ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridviewcheckboxcell(VS.80).aspx ]
in the parent DataGridView determines whether the Enabled property of the
DataGridViewDisableButtonCell in the same row is true or false.
Note
Example
Imports System
Imports System.Drawing
Imports System.Windows.Forms
Imports System.Windows.Forms.VisualStyles
Class Form1
Inherits Form
Private WithEvents dataGridView1 As New DataGridView()
<STAThread()> _
Public Shared Sub Main()
Application.EnableVisualStyles()
Application.Run(New Form1())
End Sub
dataGridView1.RowCount = 8
dataGridView1.AutoSize = True
http://msdn2.microsoft.com/en-us/library/ms171619(vs.80,d=printer).aspx 5/24/2007
How to: Disable Buttons in a Button Column in the Windows Forms DataGridView Cont... Page 2 of 7
dataGridView1.AllowUserToAddRows = False
dataGridView1.ColumnHeadersDefaultCellStyle.Alignment = _
DataGridViewContentAlignment.MiddleCenter
Me.Controls.Add(dataGridView1)
End Sub
If dataGridView1.IsCurrentCellDirty Then
dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit)
End If
End Sub
dataGridView1.Invalidate()
End If
End Sub
' If the user clicks on an enabled button cell, this event handler
' reports that the button is enabled.
Sub dataGridView1_CellClick(ByVal sender As Object, _
ByVal e As DataGridViewCellEventArgs) _
Handles dataGridView1.CellClick
If buttonCell.Enabled Then
MsgBox(dataGridView1.Rows(e.RowIndex). _
Cells(e.ColumnIndex).Value.ToString() + _
" is enabled")
End If
End If
End Sub
End Class
http://msdn2.microsoft.com/en-us/library/ms171619(vs.80,d=printer).aspx 5/24/2007
How to: Disable Buttons in a Button Column in the Windows Forms DataGridView Cont... Page 3 of 7
Return enabledValue
End Get
Set(ByVal value As Boolean)
enabledValue = value
End Set
End Property
' Override the Clone method so that the Enabled property is copied.
Public Overrides Function Clone() As Object
Dim Cell As DataGridViewDisableButtonCell = _
CType(MyBase.Clone(), DataGridViewDisableButtonCell)
Cell.Enabled = Me.Enabled
Return Cell
End Function
Else
' The button cell is enabled, so let the base class
' handle the painting.
MyBase.Paint(graphics, clipBounds, cellBounds, rowIndex, _
elementState, value, formattedValue, errorText, _
cellStyle, advancedBorderStyle, paintParts)
End If
End Sub
End Class
http://msdn2.microsoft.com/en-us/library/ms171619(vs.80,d=printer).aspx 5/24/2007
How to: Disable Buttons in a Button Column in the Windows Forms DataGridView Cont... Page 4 of 7
C# Copy Code
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles;
[STAThread]
public static void Main()
{
Application.EnableVisualStyles();
Application.Run(new Form1());
}
public Form1()
{
this.AutoSize = true;
this.Load += new EventHandler(Form1_Load);
}
dataGridView1.CellValueChanged +=
new DataGridViewCellEventHandler(dataGridView1_CellValueChanged);
dataGridView1.CurrentCellDirtyStateChanged +=
new EventHandler(dataGridView1_CurrentCellDirtyStateChanged);
dataGridView1.CellClick +=
new DataGridViewCellEventHandler(dataGridView1_CellClick);
this.Controls.Add(dataGridView1);
}
DataGridViewCheckBoxCell checkCell =
http://msdn2.microsoft.com/en-us/library/ms171619(vs.80,d=printer).aspx 5/24/2007
How to: Disable Buttons in a Button Column in the Windows Forms DataGridView Cont... Page 5 of 7
(DataGridViewCheckBoxCell)dataGridView1.
Rows[e.RowIndex].Cells["CheckBoxes"];
buttonCell.Enabled = !(Boolean)checkCell.Value;
dataGridView1.Invalidate();
}
}
if (buttonCell.Enabled)
{
MessageBox.Show(dataGridView1.Rows[e.RowIndex].
Cells[e.ColumnIndex].Value.ToString() +
" is enabled");
}
}
}
}
http://msdn2.microsoft.com/en-us/library/ms171619(vs.80,d=printer).aspx 5/24/2007
How to: Disable Buttons in a Button Column in the Windows Forms DataGridView Cont... Page 6 of 7
DataGridViewPaintParts.Background)
{
SolidBrush cellBackground =
new SolidBrush(cellStyle.BackColor);
graphics.FillRectangle(cellBackground, cellBounds);
cellBackground.Dispose();
}
See Also
Concepts
DataGridView Control Architecture (Windows Forms) [ http://msdn2.microsoft.com/en-us/library/dkdz8z4e
(VS.80).aspx ]
Column Types in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/bxt3k60s(VS.80).aspx ]
Other Resources
http://msdn2.microsoft.com/en-us/library/ms171619(vs.80,d=printer).aspx 5/24/2007
How to: Disable Buttons in a Button Column in the Windows Forms DataGridView Cont... Page 7 of 7
Community Content
http://msdn2.microsoft.com/en-us/library/ms171619(vs.80,d=printer).aspx 5/24/2007
How to: Host Controls in Windows Forms DataGridView Cells Page 1 of 8
The following code example shows how to create a calendar column. The cells of this column display dates
in ordinary text box cells, but when the user edits a cell, a DateTimePicker
[ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datetimepicker(VS.80).aspx ] control
appears. In order to avoid having to implement text box display functionality again, the CalendarCell class
derives from the DataGridViewTextBoxCell [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewtextboxcell(VS.80).aspx ] class rather than inheriting the
DataGridViewCell class directly.
Note
When you derive from DataGridViewCell or DataGridViewColumn and add new properties to the
derived class, be sure to override the Clone method to copy the new properties during cloning
operations. You should also call the base class's Clone method so that the properties of the base class
are copied to the new cell or column.
Example
Imports System
Imports System.Windows.Forms
' Ensure that the cell used for the template is a CalendarCell.
If (value IsNot Nothing) AndAlso _
Not value.GetType().IsAssignableFrom(GetType(CalendarCell)) _
Then
Throw New InvalidCastException("Must be a CalendarCell")
End If
MyBase.CellTemplate = value
End Set
End Property
End Class
http://msdn2.microsoft.com/en-us/library/7tas5c80(vs.80,d=printer).aspx 5/24/2007
How to: Host Controls in Windows Forms DataGridView Cells Page 2 of 8
' Set the value of the editing control to the current cell value.
MyBase.InitializeEditingControl(rowIndex, initialFormattedValue, _
dataGridViewCellStyle)
End Sub
End Class
Class CalendarEditingControl
Inherits DateTimePicker
Implements IDataGridViewEditingControl
Get
Return Me.Value.ToShortDateString()
End Get
End Property
Return Me.Value.ToShortDateString()
End Function
http://msdn2.microsoft.com/en-us/library/7tas5c80(vs.80,d=printer).aspx 5/24/2007
How to: Host Controls in Windows Forms DataGridView Cells Page 3 of 8
Me.Font = dataGridViewCellStyle.Font
Me.CalendarForeColor = dataGridViewCellStyle.ForeColor
Me.CalendarMonthBackground = dataGridViewCellStyle.BackColor
End Sub
Get
Return rowIndexNum
End Get
Set(ByVal value As Integer)
rowIndexNum = value
End Set
End Property
Return True
Case Else
Return False
End Select
End Function
End Sub
Get
Return False
End Get
End Property
Get
Return dataGridViewControl
End Get
Set(ByVal value As DataGridView)
dataGridViewControl = value
End Set
End Property
Get
Return valueIsChanged
End Get
Set(ByVal value As Boolean)
valueIsChanged = value
End Set
End Property
Get
http://msdn2.microsoft.com/en-us/library/7tas5c80(vs.80,d=printer).aspx 5/24/2007
How to: Host Controls in Windows Forms DataGridView Cells Page 4 of 8
Return MyBase.Cursor
End Get
End Property
' Notify the DataGridView that the contents of the cell have changed.
valueIsChanged = True
Me.EditingControlDataGridView.NotifyCurrentCellDirty(True)
MyBase.OnValueChanged(eventargs)
End Sub
End Class
<STAThreadAttribute()> _
Public Shared Sub Main()
Application.Run(New Form1())
End Sub
End Sub
End Class
C# Copy Code
using System;
using System.Windows.Forms;
http://msdn2.microsoft.com/en-us/library/7tas5c80(vs.80,d=printer).aspx 5/24/2007
How to: Host Controls in Windows Forms DataGridView Cells Page 5 of 8
public CalendarCell()
: base()
{
// Use the short date format.
this.Style.Format = "d";
}
public CalendarEditingControl()
{
this.Format = DateTimePickerFormat.Short;
}
// Implements the
// IDataGridViewEditingControl.GetEditingControlFormattedValue method.
public object GetEditingControlFormattedValue(
DataGridViewDataErrorContexts context)
{
return EditingControlFormattedValue;
}
http://msdn2.microsoft.com/en-us/library/7tas5c80(vs.80,d=printer).aspx 5/24/2007
How to: Host Controls in Windows Forms DataGridView Cells Page 6 of 8
// Implements the
// IDataGridViewEditingControl.ApplyCellStyleToEditingControl method.
public void ApplyCellStyleToEditingControl(
DataGridViewCellStyle dataGridViewCellStyle)
{
this.Font = dataGridViewCellStyle.Font;
this.CalendarForeColor = dataGridViewCellStyle.ForeColor;
this.CalendarMonthBackground = dataGridViewCellStyle.BackColor;
}
http://msdn2.microsoft.com/en-us/library/7tas5c80(vs.80,d=printer).aspx 5/24/2007
How to: Host Controls in Windows Forms DataGridView Cells Page 7 of 8
{
get
{
return valueChanged;
}
set
{
valueChanged = value;
}
}
[STAThreadAttribute()]
public static void Main()
{
Application.Run(new Form1());
}
public Form1()
{
this.dataGridView1.Dock = DockStyle.Fill;
this.Controls.Add(this.dataGridView1);
this.Load += new EventHandler(Form1_Load);
this.Text = "DataGridView calendar column demo";
}
For information about building this example from the command line for Visual Basic or Visual C#, see
Building from the Command Line (Visual Basic) [ http://msdn2.microsoft.com/en-us/library/25fz1td5
(VS.80).aspx ] or Command-Line Building [ http://msdn2.microsoft.com/en-us/library/78f4aasd
(VS.80).aspx ] . You can also build this example in Visual Studio by pasting the code into a new project.
For more information, see How to: Compile and Run a Complete Windows Forms Code Example Using
Visual Studio [ http://msdn2.microsoft.com/en-us/bb129228(vs.80).aspx ] and How to: Compile and
Run a Complete Windows Forms Code Example Using Visual Studio [ http://msdn2.microsoft.com/en-
us/bb129228(vs.90).aspx ] .
http://msdn2.microsoft.com/en-us/library/7tas5c80(vs.80,d=printer).aspx 5/24/2007
How to: Host Controls in Windows Forms DataGridView Cells Page 8 of 8
See Also
Reference
DataGridView [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview
(VS.80).aspx ]
DataGridViewColumn [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcolumn(VS.80).aspx ]
DataGridViewCell [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridviewcell
(VS.80).aspx ]
DataGridViewTextBoxCell [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewtextboxcell(VS.80).aspx ]
IDataGridViewEditingControl [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.idatagridvieweditingcontrol(VS.80).aspx ]
DateTimePicker [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datetimepicker
(VS.80).aspx ]
Concepts
DataGridView Control Architecture (Windows Forms) [ http://msdn2.microsoft.com/en-us/library/dkdz8z4e
(VS.80).aspx ]
Column Types in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/bxt3k60s(VS.80).aspx ]
Other Resources
Customizing the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/ms171618(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/7tas5c80(vs.80,d=printer).aspx 5/24/2007
Performance Tuning in the Windows Forms DataGridView Control Page 1 of 1
In This Section
Best Practices for Scaling the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/ha5xt0d9(VS.80).aspx ]
Describes how to use the DataGridView control in a way that avoids unnecessary memory usage
and performance penalties when working with large amounts of data.
Implementing Virtual Mode with Just-In-Time Data Loading in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/ms171624(VS.80).aspx ]
Describes how to load data on demand, which is useful when you have more data to display than the
available client memory can store.
Reference
DataGridView [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview
(VS.80).aspx ]
Provides reference documentation for the DataGridView control.
VirtualMode [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview.virtualmode
(VS.80).aspx ]
Provides reference documentation for the VirtualMode property.
See Also
Concepts
Data Display Modes in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/cd28yf6d(VS.80).aspx ]
Other Resources
DataGridView Control (Windows Forms) [ http://msdn2.microsoft.com/en-us/library/e0ywh3cz
(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/ms171621(vs.80,d=printer).aspx 5/24/2007
Best Practices for Scaling the Windows Forms DataGridView Control Page 1 of 6
If you have special performance needs, you can implement virtual mode and provide your own data
management operations. For more information, see Data Display Modes in the Windows Forms
DataGridView Control [ http://msdn2.microsoft.com/en-us/library/cd28yf6d(VS.80).aspx ] .
Each cell, row, and column can have its own style information. Style information is stored in
DataGridViewCellStyle [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcellstyle(VS.80).aspx ] objects. Creating cell style objects for
many individual DataGridView elements can be inefficient, especially when working with large amounts of
data. To avoid a performance impact, use the following guidelines:
http://msdn2.microsoft.com/en-us/library/ha5xt0d9(vs.80,d=printer).aspx 5/24/2007
Best Practices for Scaling the Windows Forms DataGridView Control Page 2 of 6
Each cell, row, and column can have its own shortcut menu. Shortcut menus in the DataGridView control
are represented by ContextMenuStrip [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.contextmenustrip(VS.80).aspx ] controls. Just as with cell style objects,
creating shortcut menus for many individual DataGridView elements will negatively impact performance.
To avoid this penalty, use the following guidelines:
z Avoid creating shortcut menus for individual cells and rows. This includes the row template, which is
cloned along with its shortcut menu when new rows are added to the control. For maximum
scalability, use only the control's ContextMenuStrip [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.control.contextmenustrip(VS.80).aspx ] property to specify a single
shortcut menu for the entire control.
z If you require multiple shortcut menus for multiple rows or cells, handle the
CellContextMenuStripNeeded [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.cellcontextmenustripneeded(VS.80).aspx ] or
RowContextMenuStripNeeded [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.rowcontextmenustripneeded(VS.80).aspx ] events.
These events let you manage the shortcut menu objects yourself, allowing you to tune performance.
Rows, columns, and headers can be automatically resized as cell content changes so that the entire
contents of cells are displayed without clipping. Changing sizing modes can also resize rows, columns, and
headers. To determine the correct size, the DataGridView control must examine the value of each cell that
it must accommodate. When working with large data sets, this analysis can negatively impact the
performance of the control when automatic resizing occurs. To avoid performance penalties, use the
following guidelines:
z Avoid using automatic sizing on a DataGridView control with a large set of rows. If you do use
automatic sizing, only resize based on the displayed rows. Use only the displayed rows in virtual mode
as well.
For rows and columns, use the DisplayedCells or DisplayedCellsExceptHeaders field of the
DataGridViewAutoSizeRowsMode [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewautosizerowsmode(VS.80).aspx ] ,
DataGridViewAutoSizeColumnsMode [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewautosizecolumnsmode(VS.80).aspx ] , and
DataGridViewAutoSizeColumnMode [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewautosizecolumnmode(VS.80).aspx ] enumerations.
For row headers, use the AutoSizeToDisplayedHeaders [ http://msdn2.microsoft.com/en-
us/library/ms159167(VS.80).aspx ] or AutoSizeToFirstHeader [ http://msdn2.microsoft.com/en-
us/library/ms159167(VS.80).aspx ] field of the DataGridViewRowHeadersWidthSizeMode
[ http://msdn2.microsoft.com/en-us/library/ms159167(VS.80).aspx ] enumeration.
z For maximum scalability, turn off automatic sizing and use programmatic resizing.
For more information, see Sizing Options in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/74b2wakt(VS.80).aspx ] .
z To determine whether all the cells in the DataGridView have been selected before you access the
contents of the SelectedCells collection, check the return value of the AreAllCellsSelected
[ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview.areallcellsselected
http://msdn2.microsoft.com/en-us/library/ha5xt0d9(vs.80,d=printer).aspx 5/24/2007
Best Practices for Scaling the Windows Forms DataGridView Control Page 3 of 6
(VS.80).aspx ] method. Note, however, that this method can cause rows to become unshared. For
more information, see the next section.
z Avoid using the Count [ http://msdn2.microsoft.com/en-us/library/system.collections.icollection.count
(VS.80).aspx ] property of the System.Windows.Forms.DataGridViewSelectedCellCollection
[ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridviewselectedcellcollection
(VS.80).aspx ] to determine the number of selected cells. Instead, use the
System.Windows.Forms.DataGridView.GetCellCount
(System.Windows.Forms.DataGridViewElementStates) [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.getcellcount(VS.80).aspx ] method and pass in the
System.Windows.Forms.DataGridViewElementStates.Selected [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewelementstates(VS.80).aspx ] value. Similarly, use the
System.Windows.Forms.DataGridViewRowCollection.GetRowCount
(System.Windows.Forms.DataGridViewElementStates) [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewrowcollection.getrowcount(VS.80).aspx ] and
System.Windows.Forms.DataGridViewColumnCollection.GetColumnCount
(System.Windows.Forms.DataGridViewElementStates) [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcolumncollection.getcolumncount(VS.80).aspx ]
methods to determine the number of selected elements, rather than accessing the selected row and
column collections.
z Avoid cell-based selection modes. Instead, set the
System.Windows.Forms.DataGridView.SelectionMode [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.selectionmode(VS.80).aspx ] property to
System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect [ http://msdn2.microsoft.com/en-
us/library/3c89df86(VS.80).aspx ] or
System.Windows.Forms.DataGridViewSelectionMode.FullColumnSelect
[ http://msdn2.microsoft.com/en-us/library/3c89df86(VS.80).aspx ] .
Efficient memory use is achieved in the DataGridView control through shared rows. Rows will share as
much information about their appearance and behavior as possible by sharing instances of the
DataGridViewRow class.
While sharing row instances saves memory, rows can easily become unshared. For example, whenever a
user interacts directly with a cell, its row becomes unshared. Because this cannot be avoided, the guidelines
in this topic are useful only when working with very large amounts of data and only when users will interact
with a relatively small part of the data each time your program is run.
A row cannot be shared in an unbound DataGridView control if any of its cells contain values. When the
DataGridView control is bound to an external data source or when you implement virtual mode and
provide your own data source, the cell values are stored outside the control rather than in cell objects,
allowing the rows to be shared.
A row object can only be shared if the state of all its cells can be determined from the state of the row and
the states of the columns containing the cells. If you change the state of a cell so that it can no longer be
deduced from the state of its row and column, the row cannot be shared.
z The row contains a single selected cell that is not in a selected column.
The DataGridView control will automatically attempt to use shared rows whenever rows are added to the
DataGridViewRowCollection [ http://msdn2.microsoft.com/en-
http://msdn2.microsoft.com/en-us/library/ha5xt0d9(vs.80,d=printer).aspx 5/24/2007
Best Practices for Scaling the Windows Forms DataGridView Control Page 4 of 6
Shared rows can become unshared as a result of code or user action. To avoid a performance impact, you
should avoid causing rows to become unshared. During application development, you can handle the
RowUnshared [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.rowunshared(VS.80).aspx ] event to determine when rows
become unshared. This is useful when debugging row-sharing problems.
z Avoid indexing the Rows collection or iterating through it with a foreach loop. You will not typically
need to access rows directly. DataGridView methods that operate on rows take row index arguments
rather than row instances. Additionally, handlers for row-related events receive event argument
objects with row properties that you can use to manipulate rows without causing them to become
unshared.
z If you need to access a row object, use the
System.Windows.Forms.DataGridViewRowCollection.SharedRow(System.Int32) method and
http://msdn2.microsoft.com/en-us/library/ha5xt0d9(vs.80,d=printer).aspx 5/24/2007
Best Practices for Scaling the Windows Forms DataGridView Control Page 5 of 6
pass in the row's actual index. Note, however, that modifying a shared row object retrieved through
this method will modify all the rows that share this object. The row for new records is not shared with
other rows, however, so it will not be affected when you modify any other row. Note also that different
rows represented by a shared row may have different shortcut menus. To retrieve the correct shortcut
menu from a shared row instance, use the GetContextMenuStrip [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewrow.getcontextmenustrip(VS.80).aspx ] method and
pass in the row's actual index. If you access the shared row's ContextMenuStrip
[ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridviewrow.contextmenustrip
(VS.80).aspx ] property instead, it will use the shared row index of -1 and will not retrieve the correct
shortcut menu.
z Avoid indexing the System.Windows.Forms.DataGridViewRow.Cells [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewrow.cells(VS.80).aspx ] collection. Accessing a cell
directly will cause its parent row to become unshared, instantiating a new DataGridViewRow.
Handlers for cell-related events receive event argument objects with cell properties that you can use
to manipulate cells without causing rows to become unshared. You can also use the
CurrentCellAddress [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.currentcelladdress(VS.80).aspx ] property to retrieve
the row and column indexes of the current cell without accessing the cell directly.
z Avoid cell-based selection modes. These modes cause rows to become unshared. Instead, set the
System.Windows.Forms.DataGridView.SelectionMode property to
System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect or
System.Windows.Forms.DataGridViewSelectionMode.FullColumnSelect.
z Do not handle the System.Windows.Forms.DataGridViewRowCollection.CollectionChanged
[ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewrowcollection.collectionchanged(VS.80).aspx ] or
System.Windows.Forms.DataGridView.RowStateChanged [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.rowstatechanged(VS.80).aspx ] events. These events
cause rows to become unshared. Also, do not call the
System.Windows.Forms.DataGridViewRowCollection.OnCollectionChanged
(System.ComponentModel.CollectionChangeEventArgs) [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewrowcollection.oncollectionchanged(VS.80).aspx ] or
System.Windows.Forms.DataGridView.OnRowStateChanged
(System.Int32,System.Windows.Forms.DataGridViewRowStateChangedEventArgs)
[ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview.onrowstatechanged
(VS.80).aspx ] methods, which raise these events.
z Do not access the System.Windows.Forms.DataGridView.SelectedCells collection when the
System.Windows.Forms.DataGridView.SelectionMode property value is FullColumnSelect,
ColumnHeaderSelect [ http://msdn2.microsoft.com/en-us/library/3c89df86(VS.80).aspx ] ,
FullRowSelect, or RowHeaderSelect [ http://msdn2.microsoft.com/en-us/library/3c89df86
(VS.80).aspx ] . This causes all selected rows to become unshared.
z Do not call the System.Windows.Forms.DataGridView.AreAllCellsSelected(System.Boolean)
method. This method can cause rows to become unshared.
z Do not call the System.Windows.Forms.DataGridView.SelectAll [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.selectall(VS.80).aspx ] method when the
System.Windows.Forms.DataGridView.SelectionMode property value is CellSelect
[ http://msdn2.microsoft.com/en-us/library/3c89df86(VS.80).aspx ] . This causes all rows to become
unshared.
z Do not set the ReadOnly [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcell.readonly(VS.80).aspx ] or Selected
[ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridviewcell.selected
(VS.80).aspx ] property of a cell to false when the corresponding property in its column is set to
true. This causes all rows to become unshared.
z Do not access the System.Windows.Forms.DataGridViewRowCollection.List
[ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridviewrowcollection.list
(VS.80).aspx ] property. This causes all rows to become unshared.
z Do not call the Sort(IComparer) overload of the Sort [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.sort(VS.80).aspx ] method. Sorting with a custom
comparer causes all rows to become unshared.
See Also
Tasks
http://msdn2.microsoft.com/en-us/library/ha5xt0d9(vs.80,d=printer).aspx 5/24/2007
Best Practices for Scaling the Windows Forms DataGridView Control Page 6 of 6
How to: Set Default Cell Styles for the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/k4sab6f9(VS.80).aspx ]
Reference
DataGridView [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview
(VS.80).aspx ]
Concepts
Virtual Mode in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/ms171622(VS.80).aspx ]
Data Display Modes in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/cd28yf6d(VS.80).aspx ]
Cell Styles in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/1yef90x0(VS.80).aspx ]
Sizing Options in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/74b2wakt(VS.80).aspx ]
Other Resources
Performance Tuning in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/ms171621(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/ha5xt0d9(vs.80,d=printer).aspx 5/24/2007
Virtual Mode in the Windows Forms DataGridView Control Page 1 of 4
Virtual mode is necessary only when you need to supplement or replace bound mode. In bound mode, you
set the DataSource [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.datasource(VS.80).aspx ] property and the control
automatically loads the data from the specified source and submits user changes back to it. You can control
which of the bound columns are displayed, and the data source itself typically handles operations such as
sorting.
You can supplement bound mode by displaying unbound columns along with the bound columns. This is
sometimes called "mixed mode" and is useful for displaying things like calculated values or user-interface
(UI) controls.
Because unbound columns are outside the data source, they are ignored by the data source's sorting
operations. Therefore, when you enable sorting in mixed mode, you must manage the unbound data in a
local cache and implement virtual mode to let the DataGridView control interact with it.
For more information about using virtual mode to maintain the values in unbound columns, see the
examples in the System.Windows.Forms.DataGridViewCheckBoxColumn.ThreeState
[ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcheckboxcolumn.threestate(VS.80).aspx ] property and
System.Windows.Forms.DataGridViewComboBoxColumn [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcomboboxcolumn(VS.80).aspx ] class reference topics.
If bound mode does not meet your performance needs, you can manage all your data in a custom cache
through virtual-mode event handlers. For example, you can use virtual mode to implement a just-in-time
data loading mechanism that retrieves only as much data from a networked database as is necessary for
optimal performance. This scenario is particularly useful when working with large amounts of data over a
slow network connection or with client machines that have a limited amount of RAM or storage space.
For more information about using virtual mode in a just-in-time scenario, see Implementing Virtual Mode
with Just-In-Time Data Loading in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/ms171624(VS.80).aspx ] .
Virtual-Mode Events
If your data is read-only, the CellValueNeeded event may be the only event you will need to handle.
Additional virtual-mode events let you enable specific functionality like user edits, row addition and
deletion, and row-level transactions.
Some standard DataGridView events (such as events that occur when users add or delete rows, or when
cell values are edited, parsed, validated, or formatted) are useful in virtual mode, as well. You can also
handle events that let you maintain values not typically stored in a bound data source, such as cell ToolTip
text, cell and row error text, cell and row shortcut menu data, and row height data.
http://msdn2.microsoft.com/en-us/library/ms171622(vs.80,d=printer).aspx 5/24/2007
Virtual Mode in the Windows Forms DataGridView Control Page 2 of 4
For more information about implementing virtual mode to manage read/write data with a row-level commit
scope, see Walkthrough: Implementing Virtual Mode in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/15a31akc(VS.80).aspx ] .
For an example that implements virtual mode with a cell-level commit scope, see the VirtualMode
property reference topic.
The following events occur only when the VirtualMode property is set to true.
Event Description
The following events are useful in virtual mode, but can be used regardless of the VirtualMode property
setting.
Events Description
UserDeletedRow [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.userdeletedrow
(VS.80).aspx ]
RowsRemoved [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.rowsremoved(VS.80).aspx ]
RowsAdded [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.rowsadded(VS.80).aspx ]
CellParsing [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.cellparsing(VS.80).aspx ]
CellValidating [ http://msdn2.microsoft.com/en-
http://msdn2.microsoft.com/en-us/library/ms171622(vs.80,d=printer).aspx 5/24/2007
Virtual Mode in the Windows Forms DataGridView Control Page 3 of 4
us/library/system.windows.forms.datagridview.cellvalidating(VS.80).aspx ]
CellValidated [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.cellvalidated(VS.80).aspx ]
RowValidating [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.rowvalidating(VS.80).aspx ]
RowValidated [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.rowvalidated(VS.80).aspx ]
If you are implementing virtual mode in order to work efficiently with large amounts of data, you will also
want to ensure that you are working efficiently with the DataGridView control itself. For more information
about the efficient use of cell styles, automatic sizing, selections, and row sharing, see Best Practices for
Scaling the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-us/library/ha5xt0d9
(VS.80).aspx ] .
http://msdn2.microsoft.com/en-us/library/ms171622(vs.80,d=printer).aspx 5/24/2007
Virtual Mode in the Windows Forms DataGridView Control Page 4 of 4
See Also
Tasks
Walkthrough: Implementing Virtual Mode in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/15a31akc(VS.80).aspx ]
Reference
DataGridView [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview
(VS.80).aspx ]
VirtualMode [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview.virtualmode
(VS.80).aspx ]
Concepts
Best Practices for Scaling the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/ha5xt0d9(VS.80).aspx ]
Implementing Virtual Mode with Just-In-Time Data Loading in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/ms171624(VS.80).aspx ]
Other Resources
Performance Tuning in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/ms171621(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/ms171622(vs.80,d=printer).aspx 5/24/2007
Walkthrough: Implementing Virtual Mode in the Windows Forms DataGridView Control Page 1 of 13
The DataGridView control provides several events that you can handle to interact with a custom data
store. This walkthrough guides you through the process of implementing these event handlers. The code
example in this topic uses a very simple data source for illustration purposes. In a production setting, you
will typically load only the rows you need to display into a cache, and handle DataGridView events to
interact with and update the cache. For more information, see Implementing Virtual Mode with Just-In-Time
Data Loading in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/ms171624(VS.80).aspx ]
To copy the code in this topic as a single listing, see How to: Implement Virtual Mode in the Windows Forms
DataGridView Control [ http://msdn2.microsoft.com/en-us/library/2b177d6d(VS.80).aspx ] .
Imports System
Imports System.Windows.Forms
' Declare a Customer object to store data for a row being edited.
Private customerInEdit As Customer
http://msdn2.microsoft.com/en-us/library/15a31akc(vs.80,d=printer).aspx 5/24/2007
Walkthrough: Implementing Virtual Mode in the Windows Forms DataGridView Control Page 2 of 13
<STAThreadAttribute()> _
Public Shared Sub Main()
Application.Run(New Form1())
End Sub
C# Copy Code
using System;
using System.Windows.Forms;
[STAThreadAttribute()]
public static void Main()
{
Application.Run(new Form1());
}
public Form1()
{
// Initialize the form.
this.dataGridView1.Dock = DockStyle.Fill;
this.Controls.Add(this.dataGridView1);
this.Load += new EventHandler(Form1_Load);
this.Text = "DataGridView virtual-mode demo (row-level commit scope)";
}
<br /><span space="preserve">...</span><br />}
http://msdn2.microsoft.com/en-us/library/15a31akc(vs.80,d=printer).aspx 5/24/2007
Walkthrough: Implementing Virtual Mode in the Windows Forms DataGridView Control Page 3 of 13
' Set the row count, including the row for new records.
Me.dataGridView1.RowCount = 4
End Sub
C# Copy Code
http://msdn2.microsoft.com/en-us/library/15a31akc(vs.80,d=printer).aspx 5/24/2007
Walkthrough: Implementing Virtual Mode in the Windows Forms DataGridView Control Page 4 of 13
// Set the row count, including the row for new records.
this.dataGridView1.RowCount = 4;
}
' If this is the row for new records, no values are needed.
If e.RowIndex = Me.dataGridView1.RowCount - 1 Then
Return
End If
' Store a reference to the Customer object for the row being painted.
If e.RowIndex = rowInEdit Then
customerTmp = Me.customerInEdit
Else
customerTmp = CType(Me.customers(e.RowIndex), Customer)
End If
' Set the cell value to paint using the Customer object retrieved.
Select Case Me.dataGridView1.Columns(e.ColumnIndex).Name
Case "Company Name"
e.Value = customerTmp.CompanyName
http://msdn2.microsoft.com/en-us/library/15a31akc(vs.80,d=printer).aspx 5/24/2007
Walkthrough: Implementing Virtual Mode in the Windows Forms DataGridView Control Page 5 of 13
End Sub
C# Copy Code
// Store a reference to the Customer object for the row being painted.
if (e.RowIndex == rowInEdit)
{
customerTmp = this.customerInEdit;
}
else
{
customerTmp = (Customer)this.customers[e.RowIndex];
}
// Set the cell value to paint using the Customer object retrieved.
switch (this.dataGridView1.Columns[e.ColumnIndex].Name)
{
case "Company Name":
e.Value = customerTmp.CompanyName;
break;
' Store a reference to the Customer object for the row being edited.
If e.RowIndex < Me.customers.Count Then
' If the user is editing a new row, create a new Customer object.
If Me.customerInEdit Is Nothing Then
Me.customerInEdit = New Customer( _
http://msdn2.microsoft.com/en-us/library/15a31akc(vs.80,d=printer).aspx 5/24/2007
Walkthrough: Implementing Virtual Mode in the Windows Forms DataGridView Control Page 6 of 13
CType(Me.customers(e.RowIndex), Customer).CompanyName, _
CType(Me.customers(e.RowIndex), Customer).ContactName)
End If
customerTmp = Me.customerInEdit
Me.rowInEdit = e.RowIndex
Else
customerTmp = Me.customerInEdit
End If
' Set the appropriate Customer property to the cell value entered.
Dim newValue As String = TryCast(e.Value, String)
Select Case Me.dataGridView1.Columns(e.ColumnIndex).Name
Case "Company Name"
customerTmp.CompanyName = newValue
Case "Contact Name"
customerTmp.ContactName = newValue
End Select
End Sub
C# Copy Code
// Store a reference to the Customer object for the row being edited.
if (e.RowIndex < this.customers.Count)
{
// If the user is editing a new row, create a new Customer object.
if (this.customerInEdit == null)
{
this.customerInEdit = new Customer(
((Customer)this.customers[e.RowIndex]).CompanyName,
((Customer)this.customers[e.RowIndex]).ContactName);
}
customerTmp = this.customerInEdit;
this.rowInEdit = e.RowIndex;
}
else
{
customerTmp = this.customerInEdit;
}
http://msdn2.microsoft.com/en-us/library/15a31akc(vs.80,d=printer).aspx 5/24/2007
Walkthrough: Implementing Virtual Mode in the Windows Forms DataGridView Control Page 7 of 13
}
}
End Sub
C# Copy Code
' Save row changes if any were made and release the edited
' Customer object if there is one.
If e.RowIndex >= Me.customers.Count AndAlso _
e.RowIndex <> Me.dataGridView1.Rows.Count - 1 Then
http://msdn2.microsoft.com/en-us/library/15a31akc(vs.80,d=printer).aspx 5/24/2007
Walkthrough: Implementing Virtual Mode in the Windows Forms DataGridView Control Page 8 of 13
Me.rowInEdit = -1
Me.customerInEdit = Nothing
Me.rowInEdit = -1
End If
End Sub
C# Copy Code
http://msdn2.microsoft.com/en-us/library/15a31akc(vs.80,d=printer).aspx 5/24/2007
Walkthrough: Implementing Virtual Mode in the Windows Forms DataGridView Control Page 9 of 13
End If
End Sub
C# Copy Code
8. Implement a handler for the CancelRowEdit event that discards the values of the Customer
object representing the current row.
This event occurs when the user signals row reversion by pressing ESC twice in edit mode or
once outside of edit mode. This event does not occur if no cells in the current row have been
modified or if the value of the System.Windows.Forms.QuestionEventArgs.Response
property has been set to false in a RowDirtyStateNeeded event handler.
' If the user has canceled the edit of a newly created row,
' replace the corresponding Customer object with a new, empty one.
Me.customerInEdit = New Customer()
Else
End If
End Sub
C# Copy Code
http://msdn2.microsoft.com/en-us/library/15a31akc(vs.80,d=printer).aspx 5/24/2007
Walkthrough: Implementing Virtual Mode in the Windows Forms DataGridView Cont... Page 10 of 13
System.Windows.Forms.QuestionEventArgs e)
{
if (this.rowInEdit == this.dataGridView1.Rows.Count - 2 &&
this.rowInEdit == this.customers.Count)
{
// If the user has canceled the edit of a newly created row,
// replace the corresponding Customer object with a new, empty one.
this.customerInEdit = new Customer();
}
else
{
// If the user has canceled the edit of an existing row,
// release the corresponding Customer object.
this.customerInEdit = null;
this.rowInEdit = -1;
}
}
End If
End If
End Sub
C# Copy Code
http://msdn2.microsoft.com/en-us/library/15a31akc(vs.80,d=printer).aspx 5/24/2007
Walkthrough: Implementing Virtual Mode in the Windows Forms DataGridView Cont... Page 11 of 13
if (e.Row.Index == this.rowInEdit)
{
// If the user has deleted a newly created row, release
// the corresponding Customer object.
this.rowInEdit = -1;
this.customerInEdit = null;
}
}
10. Implement a simple Customers class to represent the data items used by this code example.
End Class
C# Copy Code
http://msdn2.microsoft.com/en-us/library/15a31akc(vs.80,d=printer).aspx 5/24/2007
Walkthrough: Implementing Virtual Mode in the Windows Forms DataGridView Cont... Page 12 of 13
public Customer()
{
// Leave fields empty.
}
You will see a DataGridView control populated with three customer records. You can modify the
values of multiple cells in a row and press ESC twice in edit mode and once outside of edit mode to
revert the entire row to its original values. When you modify, add, or delete rows in the control,
Customer objects in the data store are modified, added, or deleted as well.
Next Steps
This application gives you a basic understanding of the events you must handle to implement virtual
mode in the DataGridView control. You can improve this basic application in a number of ways:
z Implement a data store that caches values from an external database. The cache should retrieve
and discard values as necessary so that it only contains what is necessary for display while
consuming a small amount of memory on the client computer.
z Fine-tune the performance of the data store depending on your requirements. For example, you
might want to compensate for slow network connections rather than client-computer memory
limitations by using a larger cache size and minimizing the number of database queries.
For more information about caching values from an external database, see How to: Implement Virtual
http://msdn2.microsoft.com/en-us/library/15a31akc(vs.80,d=printer).aspx 5/24/2007
Walkthrough: Implementing Virtual Mode in the Windows Forms DataGridView Cont... Page 13 of 13
Mode with Just-In-Time Data Loading in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/ms171625(VS.80).aspx ] .
See Also
Tasks
How to: Implement Virtual Mode in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/2b177d6d(VS.80).aspx ]
Reference
DataGridView [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview
(VS.80).aspx ]
VirtualMode [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.virtualmode(VS.80).aspx ]
CellValueNeeded [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.cellvalueneeded(VS.80).aspx ]
CellValuePushed [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.cellvaluepushed(VS.80).aspx ]
NewRowNeeded [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.newrowneeded(VS.80).aspx ]
RowValidated [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.rowvalidated(VS.80).aspx ]
RowDirtyStateNeeded [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.rowdirtystateneeded(VS.80).aspx ]
CancelRowEdit [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.cancelrowedit(VS.80).aspx ]
UserDeletingRow [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.userdeletingrow(VS.80).aspx ]
Concepts
Best Practices for Scaling the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/ha5xt0d9(VS.80).aspx ]
Implementing Virtual Mode with Just-In-Time Data Loading in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/ms171624(VS.80).aspx ]
Other Resources
Performance Tuning in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/ms171621(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/15a31akc(vs.80,d=printer).aspx 5/24/2007
How to: Implement Virtual Mode in the Windows Forms DataGridView Control Page 1 of 8
For a complete explanation of this code example, see Walkthrough: Implementing Virtual Mode in the
Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-us/library/15a31akc
(VS.80).aspx ] .
Example
Imports System
Imports System.Windows.Forms
' Declare a Customer object to store data for a row being edited.
Private customerInEdit As Customer
<STAThreadAttribute()> _
Public Shared Sub Main()
Application.Run(New Form1())
End Sub
http://msdn2.microsoft.com/en-us/library/2b177d6d(vs.80,d=printer).aspx 5/24/2007
How to: Implement Virtual Mode in the Windows Forms DataGridView Control Page 2 of 8
Me.dataGridView1.Columns.Add(contactNameColumn)
Me.dataGridView1.AutoSizeColumnsMode = _
DataGridViewAutoSizeColumnsMode.AllCells
' Set the row count, including the row for new records.
Me.dataGridView1.RowCount = 4
End Sub
' If this is the row for new records, no values are needed.
If e.RowIndex = Me.dataGridView1.RowCount - 1 Then
Return
End If
' Store a reference to the Customer object for the row being painted.
If e.RowIndex = rowInEdit Then
customerTmp = Me.customerInEdit
Else
customerTmp = CType(Me.customers(e.RowIndex), Customer)
End If
' Set the cell value to paint using the Customer object retrieved.
Select Case Me.dataGridView1.Columns(e.ColumnIndex).Name
Case "Company Name"
e.Value = customerTmp.CompanyName
End Sub
' Store a reference to the Customer object for the row being edited.
If e.RowIndex < Me.customers.Count Then
' If the user is editing a new row, create a new Customer object.
If Me.customerInEdit Is Nothing Then
Me.customerInEdit = New Customer( _
CType(Me.customers(e.RowIndex), Customer).CompanyName, _
CType(Me.customers(e.RowIndex), Customer).ContactName)
End If
customerTmp = Me.customerInEdit
Me.rowInEdit = e.RowIndex
Else
customerTmp = Me.customerInEdit
End If
' Set the appropriate Customer property to the cell value entered.
Dim newValue As String = TryCast(e.Value, String)
Select Case Me.dataGridView1.Columns(e.ColumnIndex).Name
Case "Company Name"
customerTmp.CompanyName = newValue
Case "Contact Name"
customerTmp.ContactName = newValue
End Select
End Sub
http://msdn2.microsoft.com/en-us/library/2b177d6d(vs.80,d=printer).aspx 5/24/2007
How to: Implement Virtual Mode in the Windows Forms DataGridView Control Page 3 of 8
End Sub
' Save row changes if any were made and release the edited
' Customer object if there is one.
If e.RowIndex >= Me.customers.Count AndAlso _
e.RowIndex <> Me.dataGridView1.Rows.Count - 1 Then
Me.customerInEdit = Nothing
Me.rowInEdit = -1
End If
End Sub
End If
End Sub
' If the user has canceled the edit of a newly created row,
' replace the corresponding Customer object with a new, empty one.
Me.customerInEdit = New Customer()
Else
End If
End Sub
http://msdn2.microsoft.com/en-us/library/2b177d6d(vs.80,d=printer).aspx 5/24/2007
How to: Implement Virtual Mode in the Windows Forms DataGridView Control Page 4 of 8
End If
End If
End Sub
End Class
End Class
C# Copy Code
using System;
using System.Windows.Forms;
[STAThreadAttribute()]
public static void Main()
{
Application.Run(new Form1());
http://msdn2.microsoft.com/en-us/library/2b177d6d(vs.80,d=printer).aspx 5/24/2007
How to: Implement Virtual Mode in the Windows Forms DataGridView Control Page 5 of 8
public Form1()
{
// Initialize the form.
this.dataGridView1.Dock = DockStyle.Fill;
this.Controls.Add(this.dataGridView1);
this.Load += new EventHandler(Form1_Load);
this.Text = "DataGridView virtual-mode demo (row-level commit scope)";
}
// Set the row count, including the row for new records.
this.dataGridView1.RowCount = 4;
}
// Store a reference to the Customer object for the row being painted.
if (e.RowIndex == rowInEdit)
{
customerTmp = this.customerInEdit;
}
else
{
customerTmp = (Customer)this.customers[e.RowIndex];
}
// Set the cell value to paint using the Customer object retrieved.
switch (this.dataGridView1.Columns[e.ColumnIndex].Name)
{
case "Company Name":
e.Value = customerTmp.CompanyName;
http://msdn2.microsoft.com/en-us/library/2b177d6d(vs.80,d=printer).aspx 5/24/2007
How to: Implement Virtual Mode in the Windows Forms DataGridView Control Page 6 of 8
break;
// Store a reference to the Customer object for the row being edited.
if (e.RowIndex < this.customers.Count)
{
// If the user is editing a new row, create a new Customer object.
if (this.customerInEdit == null)
{
this.customerInEdit = new Customer(
((Customer)this.customers[e.RowIndex]).CompanyName,
((Customer)this.customers[e.RowIndex]).ContactName);
}
customerTmp = this.customerInEdit;
this.rowInEdit = e.RowIndex;
}
else
{
customerTmp = this.customerInEdit;
}
http://msdn2.microsoft.com/en-us/library/2b177d6d(vs.80,d=printer).aspx 5/24/2007
How to: Implement Virtual Mode in the Windows Forms DataGridView Control Page 7 of 8
if (e.Row.Index == this.rowInEdit)
{
// If the user has deleted a newly created row, release
// the corresponding Customer object.
this.rowInEdit = -1;
this.customerInEdit = null;
}
}
}
public Customer()
{
// Leave fields empty.
}
http://msdn2.microsoft.com/en-us/library/2b177d6d(vs.80,d=printer).aspx 5/24/2007
How to: Implement Virtual Mode in the Windows Forms DataGridView Control Page 8 of 8
get
{
return contactNameValue;
}
set
{
contactNameValue = value;
}
}
}
For information about building this example from the command line for Visual Basic or Visual C#, see
Building from the Command Line (Visual Basic) [ http://msdn2.microsoft.com/en-us/library/25fz1td5
(VS.80).aspx ] or Command-Line Building [ http://msdn2.microsoft.com/en-us/library/78f4aasd
(VS.80).aspx ] . You can also build this example in Visual Studio by pasting the code into a new project.
For more information, see How to: Compile and Run a Complete Windows Forms Code Example Using
Visual Studio [ http://msdn2.microsoft.com/en-us/bb129228(vs.80).aspx ] and How to: Compile and
Run a Complete Windows Forms Code Example Using Visual Studio [ http://msdn2.microsoft.com/en-
us/bb129228(vs.90).aspx ] .
See Also
Tasks
Walkthrough: Implementing Virtual Mode in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/15a31akc(VS.80).aspx ]
Reference
DataGridView [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview
(VS.80).aspx ]
VirtualMode [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview.virtualmode
(VS.80).aspx ]
CellValueNeeded [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.cellvalueneeded(VS.80).aspx ]
CellValuePushed [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.cellvaluepushed(VS.80).aspx ]
NewRowNeeded [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.newrowneeded(VS.80).aspx ]
RowValidated [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.rowvalidated(VS.80).aspx ]
RowDirtyStateNeeded [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.rowdirtystateneeded(VS.80).aspx ]
CancelRowEdit [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.cancelrowedit(VS.80).aspx ]
UserDeletingRow [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.userdeletingrow(VS.80).aspx ]
Concepts
Virtual Mode in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/ms171622(VS.80).aspx ]
Other Resources
Performance Tuning in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/ms171621(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/2b177d6d(vs.80,d=printer).aspx 5/24/2007
Implementing Virtual Mode with Just-In-Time Data Loading in the Windows Forms Data... Page 1 of 12
If you are working with a very large table in a remote database, for example, you might want to avoid
startup delays by retrieving only the data that is necessary for display and retrieving additional data only
when the user scrolls new rows into view. If the client computers running your application have a limited
amount of memory available for storing data, you might also want to discard unused data when retrieving
new values from the database.
The following sections describe how to use a DataGridView control with a just-in-time cache.
To copy the code in this topic as a single listing, see How to: Implement Virtual Mode with Just-In-Time
Data Loading in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/ms171625(VS.80).aspx ] .
The Form
The following code example defines a form containing a read-only DataGridView control that interacts
with a Cache object through a CellValueNeeded [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.cellvalueneeded(VS.80).aspx ] event handler. The Cache
object manages the locally stored values and uses a DataRetriever object to retrieve values from the
Orders table of the sample Northwind database. The DataRetriever object, which implements the
IDataPageRetriever interface required by the Cache class, is also used to initialize the DataGridView
control rows and columns.
The IDataPageRetriever, DataRetriever, and Cache types are described later in this topic.
Note
Storing sensitive information, such as a password, within the connection string can affect the security
of your application. Using Windows Authentication (also known as integrated security) is a more
secure way to control access to a database. For more information, see Securing Connection Strings
[ http://msdn2.microsoft.com/en-us/library/89211k9b(VS.80).aspx ] .
http://msdn2.microsoft.com/en-us/library/ms171624(vs.80,d=printer).aspx 5/24/2007
Implementing Virtual Mode with Just-In-Time Data Loading in the Windows Forms Data... Page 2 of 12
End With
End Sub
End Sub
<STAThreadAttribute()> _
Public Shared Sub Main()
Application.Run(New VirtualJustInTimeDemo())
End Sub
End Class
C# Copy Code
http://msdn2.microsoft.com/en-us/library/ms171624(vs.80,d=printer).aspx 5/24/2007
Implementing Virtual Mode with Just-In-Time Data Loading in the Windows Forms Data... Page 3 of 12
DataGridViewSelectionMode.FullRowSelect;
this.dataGridView1.CellValueNeeded += new
DataGridViewCellValueEventHandler(dataGridView1_CellValueNeeded);
base.OnLoad(e);
}
[STAThreadAttribute()]
public static void Main()
{
Application.Run(new VirtualJustInTimeDemo());
}
The following code example defines the IDataPageRetriever interface, which is implemented by the
DataRetriever class. The only method declared in this interface is the SupplyPageOfData method, which
requires an initial row index and a count of the number of rows in a single page of data. These values are
used by the implementer to retrieve a subset of data from a data source.
A Cache object uses an implementation of this interface during construction to load two initial pages of
data. Whenever an uncached value is needed, the cache discards one of these pages and requests a new
page containing the value from the IDataPageRetriever.
Function SupplyPageOfData( _
ByVal lowerPageBoundary As Integer, ByVal rowsPerPage As Integer) _
As DataTable
End Interface
C# Copy Code
http://msdn2.microsoft.com/en-us/library/ms171624(vs.80,d=printer).aspx 5/24/2007
Implementing Virtual Mode with Just-In-Time Data Loading in the Windows Forms Data... Page 4 of 12
The following code example defines the DataRetriever class, which implements the IDataPageRetriever
interface to retrieve pages of data from a server. The DataRetriever class also provides Columns and
RowCount properties, which the DataGridView control uses to create the necessary columns and to add
the appropriate number of empty rows to the Rows [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.rows(VS.80).aspx ] collection. Adding the empty rows is
necessary so that the control will behave as though it contains all the data in the table. This means that the
scroll box in the scroll bar will have the appropriate size, and the user will be able to access any row in the
table. The rows are filled by the CellValueNeeded event handler only when they are scrolled into view.
End Sub
http://msdn2.microsoft.com/en-us/library/ms171624(vs.80,d=printer).aspx 5/24/2007
Implementing Virtual Mode with Just-In-Time Data Loading in the Windows Forms Data... Page 5 of 12
commaSeparatedListOfColumnNamesValue = _
commaSeparatedColumnNames.ToString()
Return commaSeparatedListOfColumnNamesValue
End Get
End Property
' Store the name of the ID column. This column must contain unique
' values so the SQL below will work properly.
If columnToSortBy Is Nothing Then
columnToSortBy = Me.Columns(0).ColumnName
End If
' Retrieve the specified number of rows from the database, starting
' with the row specified by the lowerPageBoundary parameter.
command.CommandText = _
"Select Top " & rowsPerPage & " " & _
CommaSeparatedListOfColumnNames & " From " & tableName & _
" WHERE " & columnToSortBy & " NOT IN (SELECT TOP " & _
lowerPageBoundary & " " & columnToSortBy & " From " & _
tableName & " Order By " & columnToSortBy & _
") Order By " & columnToSortBy
adapter.SelectCommand = command
End Function
End Class
C# Copy Code
http://msdn2.microsoft.com/en-us/library/ms171624(vs.80,d=printer).aspx 5/24/2007
Implementing Virtual Mode with Just-In-Time Data Loading in the Windows Forms Data... Page 6 of 12
commaSeparatedListOfColumnNamesValue =
commaSeparatedColumnNames.ToString();
return commaSeparatedListOfColumnNamesValue;
}
}
if (!this.Columns[columnToSortBy].Unique)
{
http://msdn2.microsoft.com/en-us/library/ms171624(vs.80,d=printer).aspx 5/24/2007
Implementing Virtual Mode with Just-In-Time Data Loading in the Windows Forms Data... Page 7 of 12
The following code example defines the Cache class, which manages two pages of data populated through
an IDataPageRetriever implementation. The Cache class defines an inner DataPage structure, which
contains a DataTable [ http://msdn2.microsoft.com/en-us/library/system.data.datatable(VS.80).aspx ] to
store the values in a single cache page and which calculates the row indexes that represent the upper and
lower boundaries of the page.
The Cache class loads two pages of data at construction time. Whenever the CellValueNeeded event
requests a value, the Cache object determines if the value is available in one of its two pages and, if so,
returns it. If the value is not available locally, the Cache object determines which of its two pages is
farthest from the currently displayed rows and replaces the page with a new one containing the requested
value, which it then returns.
Assuming that the number of rows in a data page is the same as the number of rows that can be displayed
on screen at once, this model allows users paging through the table to efficiently return to the most
recently viewed page.
Me.table = table
lowestIndexValue = MapToLowerBoundary(rowIndex)
highestIndexValue = MapToUpperBoundary(rowIndex)
System.Diagnostics.Debug.Assert(lowestIndexValue >= 0)
System.Diagnostics.Debug.Assert(highestIndexValue >= 0)
End Sub
http://msdn2.microsoft.com/en-us/library/ms171624(vs.80,d=printer).aspx 5/24/2007
Implementing Virtual Mode with Just-In-Time Data Loading in the Windows Forms Data... Page 8 of 12
' Return the lowest index of a page containing the given index.
Return (rowIndex \ RowsPerPage) * RowsPerPage
End Function
' Return the highest index of a page containing the given index.
Return MapToLowerBoundary(rowIndex) + RowsPerPage - 1
End Function
End Structure
dataSupply = dataSupplier
Cache.RowsPerPage = rowsPerPage
LoadFirstTwoPages()
End Sub
' Sets the value of the element parameter if the value is in the cache.
Private Function IfPageCached_ThenSetElement(ByVal rowIndex As Integer, _
ByVal columnIndex As Integer, ByRef element As String) As Boolean
Return False
End Function
End Function
End Sub
' Replace the cached page furthest from the requested cell
http://msdn2.microsoft.com/en-us/library/ms171624(vs.80,d=printer).aspx 5/24/2007
Implementing Virtual Mode with Just-In-Time Data Loading in the Windows Forms Data... Page 9 of 12
End Function
' Returns the index of the cached page most distant from the given index
' and therefore least likely to be reused.
Private Function GetIndexToUnusedPage(ByVal rowIndex As Integer) _
As Integer
End Function
' Returns a value indicating whether the given row index is contained
' in the given DataPage.
Private Function IsRowCachedInPage( _
ByVal pageNumber As Integer, ByVal rowIndex As Integer) As Boolean
End Function
End Class
C# Copy Code
http://msdn2.microsoft.com/en-us/library/ms171624(vs.80,d=printer).aspx 5/24/2007
Implementing Virtual Mode with Just-In-Time Data Loading in the Windows Forms D... Page 10 of 12
{
get
{
return highestIndexValue;
}
}
// Sets the value of the element parameter if the value is in the cache.
private bool IfPageCached_ThenSetElement(int rowIndex,
int columnIndex, ref string element)
{
if (IsRowCachedInPage(0, rowIndex))
{
element = cachePages[0].table
.Rows[rowIndex % RowsPerPage][columnIndex].ToString();
return true;
}
else if (IsRowCachedInPage(1, rowIndex))
{
element = cachePages[1].table
.Rows[rowIndex % RowsPerPage][columnIndex].ToString();
return true;
}
return false;
}
http://msdn2.microsoft.com/en-us/library/ms171624(vs.80,d=printer).aspx 5/24/2007
Implementing Virtual Mode with Just-In-Time Data Loading in the Windows Forms D... Page 11 of 12
// Returns the index of the cached page most distant from the given index
// and therefore least likely to be reused.
private int GetIndexToUnusedPage(int rowIndex)
{
if (rowIndex > cachePages[0].HighestIndex &&
rowIndex > cachePages[1].HighestIndex)
{
int offsetFromPage0 = rowIndex - cachePages[0].HighestIndex;
int offsetFromPage1 = rowIndex - cachePages[1].HighestIndex;
if (offsetFromPage0 < offsetFromPage1)
{
return 1;
}
return 0;
}
else
{
int offsetFromPage0 = cachePages[0].LowestIndex - rowIndex;
int offsetFromPage1 = cachePages[1].LowestIndex - rowIndex;
if (offsetFromPage0 < offsetFromPage1)
{
return 1;
}
return 0;
}
Additional Considerations
The previous code examples are provided as a demonstration of just-in-time data loading. You will need to
modify the code for your own needs to achieve maximum efficiency. At minimum, you will need to choose
an appropriate value for the number of rows per page of data in the cache. This value is passed into the
Cache constructor. The number of rows per page should be no less than the number of rows that can be
displayed simultaneously in your DataGridView control.
For best results, you will need to conduct performance testing and usability testing to determine the
requirements of your system and your users. Several factors that you will need to take into consideration
include the amount of memory in the client machines running your application, the available bandwidth of
the network connection used, and the latency of the server used. The bandwidth and latency should be
determined at times of peak usage.
To improve the scrolling performance of your application, you can increase the amount of data stored
locally. To improve startup time, however, you must avoid loading too much data initially. You may want to
modify the Cache class to increase the number of data pages it can store. Using more data pages can
improve scrolling efficiency, but you will need to determine the ideal number of rows in a data page,
depending on the available bandwidth and the server latency. With smaller pages, the server will be
accessed more frequently, but will take less time to return the requested data. If latency is more of an
issue than bandwidth, you may want to use larger data pages.
See Also
Tasks
Walkthrough: Implementing Virtual Mode in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/15a31akc(VS.80).aspx ]
http://msdn2.microsoft.com/en-us/library/ms171624(vs.80,d=printer).aspx 5/24/2007
Implementing Virtual Mode with Just-In-Time Data Loading in the Windows Forms D... Page 12 of 12
How to: Implement Virtual Mode with Just-In-Time Data Loading in the Windows Forms DataGridView
Control [ http://msdn2.microsoft.com/en-us/library/ms171625(VS.80).aspx ]
Reference
DataGridView [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview
(VS.80).aspx ]
VirtualMode [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview.virtualmode
(VS.80).aspx ]
Concepts
Best Practices for Scaling the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/ha5xt0d9(VS.80).aspx ]
Virtual Mode in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/ms171622(VS.80).aspx ]
Other Resources
Performance Tuning in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/ms171621(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/ms171624(vs.80,d=printer).aspx 5/24/2007
How to: Implement Virtual Mode with Just-In-Time Data Loading in the Windows Forms... Page 1 of 11
Example
Imports System.Data
Imports System.Data.SqlClient
Imports System.Drawing
Imports System.Windows.Forms
http://msdn2.microsoft.com/en-us/library/ms171625(vs.80,d=printer).aspx 5/24/2007
How to: Implement Virtual Mode with Just-In-Time Data Loading in the Windows Forms... Page 2 of 11
End Try
End Sub
End Sub
<STAThreadAttribute()> _
Public Shared Sub Main()
Application.Run(New VirtualJustInTimeDemo())
End Sub
End Class
Function SupplyPageOfData( _
ByVal lowerPageBoundary As Integer, ByVal rowsPerPage As Integer) _
As DataTable
End Interface
End Sub
http://msdn2.microsoft.com/en-us/library/ms171625(vs.80,d=printer).aspx 5/24/2007
How to: Implement Virtual Mode with Just-In-Time Data Loading in the Windows Forms... Page 3 of 11
End Get
End Property
commaSeparatedListOfColumnNamesValue = _
commaSeparatedColumnNames.ToString()
Return commaSeparatedListOfColumnNamesValue
End Get
End Property
' Store the name of the ID column. This column must contain unique
' values so the SQL below will work properly.
If columnToSortBy Is Nothing Then
columnToSortBy = Me.Columns(0).ColumnName
End If
' Retrieve the specified number of rows from the database, starting
' with the row specified by the lowerPageBoundary parameter.
command.CommandText = _
"Select Top " & rowsPerPage & " " & _
CommaSeparatedListOfColumnNames & " From " & tableName & _
" WHERE " & columnToSortBy & " NOT IN (SELECT TOP " & _
lowerPageBoundary & " " & columnToSortBy & " From " & _
tableName & " Order By " & columnToSortBy & _
") Order By " & columnToSortBy
adapter.SelectCommand = command
End Function
End Class
http://msdn2.microsoft.com/en-us/library/ms171625(vs.80,d=printer).aspx 5/24/2007
How to: Implement Virtual Mode with Just-In-Time Data Loading in the Windows Forms... Page 4 of 11
Me.table = table
lowestIndexValue = MapToLowerBoundary(rowIndex)
highestIndexValue = MapToUpperBoundary(rowIndex)
System.Diagnostics.Debug.Assert(lowestIndexValue >= 0)
System.Diagnostics.Debug.Assert(highestIndexValue >= 0)
End Sub
' Return the lowest index of a page containing the given index.
Return (rowIndex \ RowsPerPage) * RowsPerPage
End Function
' Return the highest index of a page containing the given index.
Return MapToLowerBoundary(rowIndex) + RowsPerPage - 1
End Function
End Structure
dataSupply = dataSupplier
Cache.RowsPerPage = rowsPerPage
LoadFirstTwoPages()
End Sub
' Sets the value of the element parameter if the value is in the cache.
Private Function IfPageCached_ThenSetElement(ByVal rowIndex As Integer, _
ByVal columnIndex As Integer, ByRef element As String) As Boolean
Return False
End Function
End Function
http://msdn2.microsoft.com/en-us/library/ms171625(vs.80,d=printer).aspx 5/24/2007
How to: Implement Virtual Mode with Just-In-Time Data Loading in the Windows Forms... Page 5 of 11
End Sub
' Replace the cached page furthest from the requested cell
' with a new page containing the newly retrieved data.
cachePages(GetIndexToUnusedPage(rowIndex)) = _
New DataPage(table, rowIndex)
End Function
' Returns the index of the cached page most distant from the given index
' and therefore least likely to be reused.
Private Function GetIndexToUnusedPage(ByVal rowIndex As Integer) _
As Integer
End Function
' Returns a value indicating whether the given row index is contained
' in the given DataPage.
Private Function IsRowCachedInPage( _
ByVal pageNumber As Integer, ByVal rowIndex As Integer) As Boolean
End Function
End Class
C# Copy Code
using System;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Windows.Forms;
http://msdn2.microsoft.com/en-us/library/ms171625(vs.80,d=printer).aspx 5/24/2007
How to: Implement Virtual Mode with Just-In-Time Data Loading in the Windows Forms... Page 6 of 11
base.OnLoad(e);
}
[STAThreadAttribute()]
public static void Main()
{
Application.Run(new VirtualJustInTimeDemo());
}
http://msdn2.microsoft.com/en-us/library/ms171625(vs.80,d=printer).aspx 5/24/2007
How to: Implement Virtual Mode with Just-In-Time Data Loading in the Windows Forms... Page 7 of 11
commaSeparatedListOfColumnNamesValue =
commaSeparatedColumnNames.ToString();
http://msdn2.microsoft.com/en-us/library/ms171625(vs.80,d=printer).aspx 5/24/2007
How to: Implement Virtual Mode with Just-In-Time Data Loading in the Windows Forms... Page 8 of 11
return commaSeparatedListOfColumnNamesValue;
}
}
if (!this.Columns[columnToSortBy].Unique)
{
throw new InvalidOperationException(String.Format(
"Column {0} must contain unique values.", columnToSortBy));
}
http://msdn2.microsoft.com/en-us/library/ms171625(vs.80,d=printer).aspx 5/24/2007
How to: Implement Virtual Mode with Just-In-Time Data Loading in the Windows Forms... Page 9 of 11
// Sets the value of the element parameter if the value is in the cache.
private bool IfPageCached_ThenSetElement(int rowIndex,
int columnIndex, ref string element)
{
if (IsRowCachedInPage(0, rowIndex))
{
element = cachePages[0].table
.Rows[rowIndex % RowsPerPage][columnIndex].ToString();
return true;
}
else if (IsRowCachedInPage(1, rowIndex))
{
element = cachePages[1].table
.Rows[rowIndex % RowsPerPage][columnIndex].ToString();
return true;
}
return false;
}
// Returns the index of the cached page most distant from the given index
// and therefore least likely to be reused.
private int GetIndexToUnusedPage(int rowIndex)
http://msdn2.microsoft.com/en-us/library/ms171625(vs.80,d=printer).aspx 5/24/2007
How to: Implement Virtual Mode with Just-In-Time Data Loading in the Windows For... Page 10 of 11
{
if (rowIndex > cachePages[0].HighestIndex &&
rowIndex > cachePages[1].HighestIndex)
{
int offsetFromPage0 = rowIndex - cachePages[0].HighestIndex;
int offsetFromPage1 = rowIndex - cachePages[1].HighestIndex;
if (offsetFromPage0 < offsetFromPage1)
{
return 1;
}
return 0;
}
else
{
int offsetFromPage0 = cachePages[0].LowestIndex - rowIndex;
int offsetFromPage1 = cachePages[1].LowestIndex - rowIndex;
if (offsetFromPage0 < offsetFromPage1)
{
return 1;
}
return 0;
}
z Access to a server with the Northwind SQL Server sample database installed.
For information about building this example from the command line for Visual Basic or Visual C#, see
Building from the Command Line (Visual Basic) [ http://msdn2.microsoft.com/en-us/library/25fz1td5
(VS.80).aspx ] or Command-Line Building [ http://msdn2.microsoft.com/en-us/library/78f4aasd
(VS.80).aspx ] . You can also build this example in Visual Studio by pasting the code into a new project.
For more information, see How to: Compile and Run a Complete Windows Forms Code Example Using
Visual Studio [ http://msdn2.microsoft.com/en-us/bb129228(vs.80).aspx ] and How to: Compile and
Run a Complete Windows Forms Code Example Using Visual Studio [ http://msdn2.microsoft.com/en-
us/bb129228(vs.90).aspx ] .
Security
Storing sensitive information, such as a password, within the connection string can affect the security of
your application. Using Windows Authentication (also known as integrated security) is a more secure way to
control access to a database. For more information, see Securing Connection Strings
[ http://msdn2.microsoft.com/en-us/library/89211k9b(VS.80).aspx ] .
See Also
Reference
DataGridView [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview
(VS.80).aspx ]
VirtualMode [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview.virtualmode
(VS.80).aspx ]
CellValueNeeded [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.cellvalueneeded(VS.80).aspx ]
Concepts
Implementing Virtual Mode with Just-In-Time Data Loading in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/ms171624(VS.80).aspx ]
http://msdn2.microsoft.com/en-us/library/ms171625(vs.80,d=printer).aspx 5/24/2007
How to: Implement Virtual Mode with Just-In-Time Data Loading in the Windows For... Page 11 of 11
Community Content
http://msdn2.microsoft.com/en-us/library/ms171625(vs.80,d=printer).aspx 5/24/2007
Default Keyboard and Mouse Handling in the Windows Forms DataGridView Control Page 1 of 5
Note
To customize keyboard behavior, you can handle standard keyboard events such as KeyDown
[ http://msdn2.microsoft.com/en-us/library/system.windows.forms.control.keydown(VS.80).aspx ] .
In edit mode, however, the hosted editing control receives the keyboard input and the keyboard
events do not occur for the DataGridView control. To handle editing control events, attach your
handlers to the editing control in an EditingControlShowing [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.editingcontrolshowing(VS.80).aspx ] event handler.
Alternatively, you can customize keyboard behavior in a DataGridView subclass by overriding the
ProcessDialogKey [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.processdialogkey(VS.80).aspx ] and
ProcessDataGridViewKey [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.processdatagridviewkey(VS.80).aspx ] methods.
Key or key
combination Description
DOWN ARROW Moves the focus to the cell directly below the current cell. If the focus is in
the last row, does nothing.
LEFT ARROW Moves the focus to the previous cell in the row. If the focus is in the first cell
in the row, does nothing.
RIGHT ARROW Moves the focus to the next cell in the row. If the focus is in the last cell in
the row, does nothing.
UP ARROW Moves the focus to the cell directly above the current cell. If the focus is in
the first row, does nothing.
HOME Moves the focus to the first cell in the current row.
END Moves the focus to the last cell in the current row.
PAGE DOWN Scrolls the control downward by the number of rows that are fully displayed.
Moves the focus to the last fully displayed row without changing columns.
PAGE UP Scrolls the control upward by the number of rows that are fully displayed.
Moves focus to the first displayed row without changing columns.
http://msdn2.microsoft.com/en-us/library/tb9t9a2t(vs.80,d=printer).aspx 5/24/2007
Default Keyboard and Mouse Handling in the Windows Forms DataGridView Control Page 2 of 5
cell in the next row. If the focus is in the last cell in the control, moves the
focus to the next control in the tab order of the parent container.
If the StandardTab property value is true, moves the focus to the next
control in the tab order of the parent container.
SHIFT+TAB If the StandardTab property value is false, moves the focus to the previous
cell in the current row. If the focus is already in the first cell of the row,
moves the focus to the last cell in the previous row. If the focus is in the first
cell in the control, moves the focus to the previous control in the tab order of
the parent container.
If the StandardTab property value is true, moves the focus to the previous
control in the tab order of the parent container.
CTRL+TAB If the StandardTab property value is false, moves the focus to the next
control in the tab order of the parent container.
If the StandardTab property value is true, moves the focus to the next cell
in the current row. If the focus is already in the last cell of the row, moves
the focus to the first cell in the next row. If the focus is in the last cell in the
control, moves the focus to the next control in the tab order of the parent
container.
CTRL+SHIFT+TAB If the StandardTab property value is false, moves the focus to the previous
control in the tab order of the parent container.
If the StandardTab property value is true, moves the focus to the previous
cell in the current row. If the focus is already in the first cell of the row,
moves the focus to the last cell in the previous row. If the focus is in the first
cell in the control, moves the focus to the previous control in the tab order of
the parent container.
CTRL+ARROW Moves the focus to the farthest cell in the direction of the arrow.
F2 Puts the current cell into cell edit mode if the EditMode
[ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.editmode(VS.80).aspx ]
property value is EditOnF2 [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridvieweditmode(VS.80).aspx ] or
EditOnKeystrokeOrF2 [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridvieweditmode(VS.80).aspx ] .
ALT+UP/DOWN If the current cell is a DataGridViewComboBoxCell, puts the cell into edit
ARROW mode and displays the drop-down list.
http://msdn2.microsoft.com/en-us/library/tb9t9a2t(vs.80,d=printer).aspx 5/24/2007
Default Keyboard and Mouse Handling in the Windows Forms DataGridView Control Page 3 of 5
[ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewbuttoncell(VS.80).aspx ] ,
DataGridViewLinkCell [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewlinkcell(VS.80).aspx ] , or
DataGridViewCheckBoxCell [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridviewcheckboxcell(VS.80).aspx ] ,
raises the CellClick [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.cellclick(VS.80).aspx ] and
CellContentClick [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.cellcontentclick(VS.80).aspx ]
events. If the current cell is a DataGridViewButtonCell, also presses the
button. If the current cell is a DataGridViewCheckBoxCell, also changes
the check state.
ENTER Commits any changes to the current cell and row and moves the focus to the
cell directly below the current cell. If the focus is in the last row, commits
any changes without moving the focus.
ESC If the control is in edit mode, cancels the edit. If the control is not in edit
mode, reverts any changes that have been made to the current row if the
control is bound to a data source that supports editing or virtual mode has
been implemented with row-level commit scope.
BACKSPACE Deletes the character before the insertion point when editing a cell.
DELETE Deletes the character after the insertion point when editing a cell.
CTRL+ENTER Commits any changes to the current cell without moving the focus. Also
commits any changes to the current row if the control is bound to a data
source that supports editing or virtual mode has been implemented with
row-level commit scope.
Selection Keys
If the MultiSelect [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.multiselect(VS.80).aspx ] property is set to false and
the SelectionMode [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.datagridview.selectionmode(VS.80).aspx ] property is set to CellSelect
[ http://msdn2.microsoft.com/en-us/library/3c89df86(VS.80).aspx ] , changing the current cell by using
the navigation keys changes the selection to the new cell. The SHIFT, CTRL, and ALT keys do not affect
this behavior.
SHIFT+SPACEBAR Selects the full row or column (the same as clicking the row or
column header).
http://msdn2.microsoft.com/en-us/library/tb9t9a2t(vs.80,d=printer).aspx 5/24/2007
Default Keyboard and Mouse Handling in the Windows Forms DataGridView Control Page 4 of 5
navigation key (arrow key, If a full row or column is selected, changing the current cell to a
PAGE UP/DOWN, HOME, END) new row or column moves the selection to the full new row or
column (depending on the selection mode).
If MultiSelect is set to true, the navigation behavior does not change, but navigating with the
keyboard while pressing SHIFT (including CTRL+SHIFT) will modify a multi-cell selection. Before
navigation begins, the control marks the current cell as an anchor cell. When you navigate while
pressing SHIFT, the selection includes all cells between the anchor cell and the current cell. Other cells
in the control will remain selected if they were already selected, but they may become unselected if the
keyboard navigation temporarily puts them between the anchor cell and the current cell.
Note
Clicking a cell with the left mouse button always changes the current cell. Clicking a cell with the
right mouse button opens a shortcut menu, when one is available.
Mouse
action Description
Left Makes the clicked cell the current cell, and raises the
mouse System.Windows.Forms.DataGridView.CellMouseDown
button [ http://msdn2.microsoft.com/en-
down us/library/system.windows.forms.datagridview.cellmousedown(VS.80).aspx ] event.
Mouse Selection
No selection behavior is associated with the middle mouse button or the mouse wheel.
If the MultiSelect property is set to false and the SelectionMode property is set to CellSelect, the
following behavior occurs.
http://msdn2.microsoft.com/en-us/library/tb9t9a2t(vs.80,d=printer).aspx 5/24/2007
Default Keyboard and Mouse Handling in the Windows Forms DataGridView Control Page 5 of 5
Click left mouse Selects only the current cell if the user clicks a cell. No selection behavior if
button the user clicks a row or column header.
If MultiSelect is set to true, clicking a cell while pressing CTRL or SHIFT will modify a multi-cell
selection.
When you click a cell while pressing CTRL, the cell will change its selection state while all other cells
retain their current selection state.
When you click a cell or a series of cells while pressing SHIFT, the selection includes all cells between
the current cell and an anchor cell located at the position of the current cell before the first click. When
you click and drag the pointer across multiple cells, the anchor cell is the cell clicked at the beginning of
the drag operation. Subsequent clicks while pressing SHIFT change the current cell, but not the anchor
cell. Other cells in the control will remain selected if they were already selected, but they may become
unselected if mouse navigation temporarily puts them between the anchor cell and the current cell.
See Also
Reference
DataGridView [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview
(VS.80).aspx ]
Other Resources
DataGridView Control (Windows Forms) [ http://msdn2.microsoft.com/en-us/library/e0ywh3cz
(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/tb9t9a2t(vs.80,d=printer).aspx 5/24/2007
Differences Between the Windows Forms DataGridView and DataGrid Controls Page 1 of 2
The following table describes a few of the primary features available in the DataGridView control that are
missing from the DataGrid control.
DataGridView
control feature Description
Multiple column The DataGridView control provides more built-in column types than the
types DataGrid control. These column types meet the needs of most common
scenarios, but are also easier to extend or replace than the column types in
the DataGrid control. For more information, see Column Types in the
Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/bxt3k60s(VS.80).aspx ] .
Multiple ways to The DataGrid control is limited to displaying data from an external data
display data source. The DataGridView control, however, can display unbound data stored
in the control, data from a bound data source, or bound and unbound data
together. You can also implement virtual mode in the DataGridView control
to provide custom data management. For more information, see Data Display
Modes in the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/cd28yf6d(VS.80).aspx ] .
Multiple ways to The DataGridView control provides many properties and events that enable
customize the you to specify how data is formatted and displayed. For example, you can
display of data change the appearance of cells, rows, and columns depending on the data
they contain, or you can replace data of one data type with equivalent data of
another type. For more information, see Data Formatting in the Windows
Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/hezscd0d(VS.80).aspx ] .
Multiple options for The DataGridView control enables you to work with individual grid
changing cell, row, components in numerous ways. For example, you can freeze rows and
column, and header columns to prevent them from scrolling; hide rows, columns, and headers;
appearance and change the way row, column, and header sizes are adjusted; change the way
behavior users make selections; and provide ToolTips and shortcut menus for individual
cells, rows, and columns.
The DataGrid control is retained for backward compatibility and for special needs. For nearly all purposes,
you should use the DataGridView control. The only feature that is available in the DataGrid control that is
not available in the DataGridView control is the hierarchical display of information from two related tables
in a single control. You must use two DataGridView controls to display information from two tables that
are in a master/detail relationship.
If you have existing applications that use the DataGrid control in a simple data-bound scenario without
customizations, you can simply replace the old control with the new control. Both controls use the standard
http://msdn2.microsoft.com/en-us/library/ms171628(vs.80,d=printer).aspx 5/24/2007
Differences Between the Windows Forms DataGridView and DataGrid Controls Page 2 of 2
Windows Forms data-binding architecture, so the DataGridView control will display your bound data with
no additional configuration needed. You might want to consider taking advantage of data-binding
improvements, however, by binding your data to a BindingSource [ http://msdn2.microsoft.com/en-
us/library/system.windows.forms.bindingsource(VS.80).aspx ] component, which you can then bind to the
DataGridView control. For more information, see BindingSource Component
[ http://msdn2.microsoft.com/en-us/library/h974h4y2(VS.80).aspx ] .
Because the DataGridView control has an entirely new architecture, there is no straightforward conversion
path that will enable you to use DataGrid customizations with the DataGridView control. Many DataGrid
customizations are unnecessary with the DataGridView control, however, because of the built-in features
available in the new control. If you have created custom column types for the DataGrid control that you
want to use with the DataGridView control, you will have to implement them again using the new
architecture. For more information, see Customizing the Windows Forms DataGridView Control
[ http://msdn2.microsoft.com/en-us/library/ms171618(VS.80).aspx ] .
See Also
Reference
DataGridView [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview
(VS.80).aspx ]
DataGrid [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagrid(VS.80).aspx ]
BindingSource [ http://msdn2.microsoft.com/en-us/library/system.windows.forms.bindingsource
(VS.80).aspx ]
Concepts
Column Types in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/bxt3k60s(VS.80).aspx ]
Cell Styles in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/1yef90x0(VS.80).aspx ]
Data Display Modes in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/cd28yf6d(VS.80).aspx ]
Data Formatting in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/hezscd0d(VS.80).aspx ]
Sizing Options in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/74b2wakt(VS.80).aspx ]
Column Sort Modes in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/95scxcdy(VS.80).aspx ]
Selection Modes in the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/8x6w9028(VS.80).aspx ]
Other Resources
DataGridView Control (Windows Forms) [ http://msdn2.microsoft.com/en-us/library/e0ywh3cz
(VS.80).aspx ]
DataGrid Control (Windows Forms) [ http://msdn2.microsoft.com/en-us/library/keb37h7b(VS.80).aspx ]
BindingSource Component [ http://msdn2.microsoft.com/en-us/library/h974h4y2(VS.80).aspx ]
Customizing the Windows Forms DataGridView Control [ http://msdn2.microsoft.com/en-
us/library/ms171618(VS.80).aspx ]
Community Content
http://msdn2.microsoft.com/en-us/library/ms171628(vs.80,d=printer).aspx 5/24/2007