C# DataGridView Tips
C# DataGridView Tips
Go
Intro
First, you should use DataGridView when you need to
display information that is easily broken up into columns.
This includes numbers, names, IDs and other attributes
stored in a database (numbers and strings).
Tip:
You can use the DataSource
property to hook your DataGridView
up to a database or an object
collection.
/// <summary>
/// Used to set up the data table when the user types a query.
/// </summary>
void BuildDataGrid()
{
dataGridView1.DataSource = GetSearchResults(queryStr);
}
/// <summary>
/// Connect to the database.
/// And then use an adapter to fill a DataTable.
/// </summary>
DataTable GetSearchResults(string queryStr)
{
//
// Make a new DataTable.
//
DataTable table = new DataTable();
//
// You will want to declare a new DataAdapter,
// and then call its fill method on the DataTable.
//
return table;
}
Then:
It fills a new DataTable.
We can use an SqlDataAdapter to fill this DataTable
object.
The results appear in your DataGridView.
SqlDataAdapter Example
DataAdapter
In the .NET Framework, a
DataAdapter class is an
object that uses internal logic
to take data from a database
and into an object. You will
need to add the database and
SQL statements. These
statements depend on the database.
And:
This topic is more in the ADO.NET realm, but these
objects are extremely useful in many programs that use
DataGridView.
Objects
Here we use a collection with an implementation of IList,
which is an interface shared by Lists and arrays. One great
feature is that .NET will read the property names of your
collection objects automatically.
So:
Simply create a new List or array of objects, and set the
DataSource to this.
/// <summary>
www.dotnetperls.com/datagridview-tips 2/11
1/14/14 C# DataGridView Tips
/// The test class for our example.
/// </summary>
class TestObject
{
public int OneValue { get; set; }
public int TwoValue { get; set; }
}
void M()
{
TestObject test1 = new TestObject()
{
OneValue = 2,
TwoValue = 3
};
List<TestObject> list = new List<TestObject>();
list.Add(test1);
list.Add(test2); // Not shown in code
dataGridView1.DataSource = list;
}
And:
These aren't useful for many
kinds of applications. Disable
row headers by setting
RowHeadersVisible to false.
Tip:
This will provide the appearance in the screenshots,
which is more streamlined.
Tabbing
You can make tabbing work in your DataGridView control
by modifying the StandardTab property. This property lets
you make sure that when your user tabs around your
window, the tabbing events don't get stuck in the
DataGridView.
Tip:
Use StandardTab in the designer to make the tab key
move out of the DataGridView and to the next control.
www.dotnetperls.com/datagridview-tips 3/11
1/14/14 C# DataGridView Tips
Add rows
You can add rows to the DataGridView
by using the instance Add method in
C# code. This method adds rows to the
DataGridView programmatically. There
is a collection called Rows on the
DataGridView.
Rows:
On the rows collection, there is a method called Add.
However, it is usually better to modify the DataSource.
/// <summary>
/// Shows example usage of Add method on Rows.
/// </summary>
void M()
{
//
// n is the new index. The cells must also be accessed by an index.
// In this example, there are four cells in each row.
//
int n = dataGridView1.Rows.Add();
dataGridView1.Rows[n].Cells[0].Value = title;
dataGridView1.Rows[n].Cells[1].Value = dateTimeNow;
//
// The second cell is a date cell, use typeof(DateTime).
//
dataGridView1.Rows[n].Cells[1].ValueType = typeof(DateTime);
dataGridView1.Rows[n].Cells[2].Value = wordCount;
}
Note:
The code modifies the new row. Add will give us the
index of the new row, so we can modify that row in-
place.
typeof.
DateTime Examples
Typeof Operator
Configure columns
You will find that Visual Studio provides
dialogs that allow you to configure the
columns in your DataGridView. Columns are
used as templates for how your DataGridView renders
columnar data.
But:
They do not actually contain the data, just the rules for
rendering it to the screen.
DataGridView Columns, Edit Columns Dialog
Here:
We only take the Y coordinate of the current cell. The
current cell is also the selected cell, which usually has a
blue highlight.
/// <summary>
/// Shows example usage of how to get the current cell.
/// </summary>
void M()
{
//
// Go from Y coordinate to a selected cell's value.
// DateTime is just for this example, and the Cells[1] part just
// takes the second cell for this example.
//
www.dotnetperls.com/datagridview-tips 5/11
1/14/14 C# DataGridView Tips
int yCoord = dataGridView1.CurrentCellAddress.Y; // You can get X if you need it.
DateTime thisDate = (DateTime)dataGridView1.Rows[yCoord].Cells[1].Value;
}
Double-clicks
We can use the CellDoubleClick event and
check RowIndex. In the event handler for
CellDoubleClick, call a method that handles
the item. Note that you must check for
e.RowIndex equals -1.
Tip:
When RowIndex is -1, it indicates that the column
headers were double-clicked and not a regular cell.
SelectionChanged
You can update your program's buttons
instantly when the user selects a cell in the
DataGridView. Here we need to listen for
SelectionChanged and change controls
based on the selection.
CurrentCellAddress:
We can check for CurrentCellAddress to
figure out what was selected and where the selection
moved.
/// <summary>
/// Custom method that sets the Enabled property of a button.
/// </summary>
void SetupButtons()
{
//
// Disable openButton when there are no items shown.
//
openButton.Enabled = (dataGridView1.RowCount > 0);
}
Note:
The user interface will respond instantly when selection
is changed. People love it when programs work better
than expected.
Expand columns
You can specify that the columns in
your DataGridView should expand by
setting Columns.AutoSizeMode to Fill.
This causes the cells to expand to fill
the horizontal area. Then, in the
designer, set some cells to fixed or
percentage width.
Tip:
Just allow one column to fill up the remainder. You will
www.dotnetperls.com/datagridview-tips 7/11
1/14/14 C# DataGridView Tips
Alternating colors
It is also possible to configure your
DataGridView so that the row colors
alternate. This is useful for reducing
errors caused by rows looking too similar
to the program's users. Please check out
the tutorial on rows and colors.
DataGridView Colors
Appearance
You can improve the appearance of DataGridView with
conditional code. In Windows Vista, DataGridView looks
best without a border. But in Windows XP it looks best with
one. We return the appropriate border attributes based on
the OS.
/// <summary>
/// Remove the column header border in the Aero theme in Vista,
/// but keep it for other themes such as standard and classic.
/// </summary>
static DataGridViewHeaderBorderStyle ProperColumnHeadersBorderStyle
{
get
{
return (SystemFonts.MessageBoxFont.Name == "Segoe UI") ?
DataGridViewHeaderBorderStyle.None :
DataGridViewHeaderBorderStyle.Raised;
}
}
}
www.dotnetperls.com/datagridview-tips 8/11
1/14/14 C# DataGridView Tips
PreviewKeyDown
When your DataGridView handles events such as KeyDown,
the PreviewKeyDown event can be used to filter some of
these events, preventing incorrect behavior. This solves
complex problems related to key input.
PreviewKeyDown
VB.NET
The VB.NET language can
use the DataGridView
control. In it, the event
handlers in the source code have different declarations.
And VB.NET programs use different default identifiers for
Windows Forms controls.
Note:
This site has a complete tutorial on the DataGridView
control in the VB.NET language.
DataGridView Examples
Misc.
Let's look at some
miscellaneous tips related to
the DataGridView control.
These were useful to me at
some point, but are not
important or may not be ideal. If something is helpful, I
will try to expand it.
SortGlyphDirection:
www.dotnetperls.com/datagridview-tips 9/11
1/14/14 C# DataGridView Tips
BackgroundColor:
Setting this to 'Window' often looks best.
Looks professional when you adjust this.
SelectionMode:
The FullRowSelect enum value looks the best when you
are displaying simple result rows.
ColumnHeaderMouseClick:
This event is used to capture when a header is clicked.
Can be used with ColumnIndex.
ColumnIndex:
Sometimes you may need to modify the direction of the
sort glyph. You can check e.ColumnIndex on the event
parameter.
List
It is possible to display a List in
your DataGridView, even if the
List does not display properly by
assigning it to the DataSource
directly. You can convert the
List to a DataTable, which can then be displayed in the
DataGridView.
Convert List to DataTable: DataGridView
Tutorial
There is a related tutorial on this
web site. It helps if you are
confused by some aspects of
DataGridView that aren't shown
here, such as the Columns
collections, how to make
alternating row colors, or how to use SqlDataAdapter.
DataGridView Tutorial
DataGrid:
WPF is a framework similar to Windows Forms, but
newer.
It uses a DataGrid control, not a DataGridView.
We describe DataGrid.
www.dotnetperls.com/datagridview-tips 10/11
1/14/14 C# DataGridView Tips
DataGrid
Summary
We improved the usability and
appearance of the
DataGridView in a program
with these methods. No one
loves developing with
DataGridView, but a good one
can really make your program
shine.
Review:
DataGridView is ideal in the .NET Framework and C#
language for viewing information from databases or
object collections.
www.dotnetperls.com/datagridview-tips 11/11