0% found this document useful (0 votes)
231 views

C# DataGridView Tips

The document provides tips for improving the usability and appearance of the C# DataGridView control. It discusses setting the DataSource property to bind the control to a database or object collection. It also covers hiding row headers, configuring tabbing behavior, adding and modifying rows programmatically, configuring columns, locating the current cell, handling double clicks, and responding to selection changes. The tips are accompanied by code examples to demonstrate implementation.

Uploaded by

Jeevan Kharel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
231 views

C# DataGridView Tips

The document provides tips for improving the usability and appearance of the C# DataGridView control. It discusses setting the DataSource property to bind the control to a database or object collection. It also covers hiding row headers, configuring tabbing behavior, adding and modifying rows programmatically, configuring columns, locating the current cell, handling double clicks, and responding to selection changes. The tips are accompanied by code examples to demonstrate implementation.

Uploaded by

Jeevan Kharel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

1/14/14 C# DataGridView Tips

Go

C# DataGridView C#: Windows

DataGridView displays the


contents of a data source. It is a
control in Windows Forms. It uses
a grid format. There are many
ways to improve its default
configuration. We show some
improvements to usability and
appearance.

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.

Example that sets DataSource: C#

/// <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;
}

After BuildDataGrid is called, the above code sets the


www.dotnetperls.com/datagridview-tips 1/11
1/14/14 C# DataGridView Tips

DataSource property to the results of


another function, GetSearchResults.
Next, it performs a custom search.
This is custom code that will query a
database for results.

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.

Example that uses object collection: C#

/// <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;
}

Hide row headers


You can hide row headers in the
DataGridView control by using
the RowHeadersVisible property.
When you create a new
DataGridView, there will be ugly
row headers with arrows in the
leftmost column.

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.

Example that adds rows: C#

/// <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;
}

In this example, we call Add


on Rows. The DataGridView
has a Rows collection, which is
simply a list of rows in the
data grid. Add is an instance
method on this collection. It
returns an index of the newly-added row.

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.

The code sets ValueType on cells. Every cell in the data


grid has a ValueType property. Usually, you don't need to
worry about this. But if you want to specify a DateTime
column, you can change it by assigning it to a type, using
www.dotnetperls.com/datagridview-tips 4/11
1/14/14 C# DataGridView Tips

typeof.
DateTime Examples
Typeof Operator

Users can add rows. With the


DataGridView control, users can add rows to
your program on their own if you do not
disallow it. A separate article focuses on
managing user-created data in the
DataGridView.
DataGridView Add Rows

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

Locate current cell


You can locate the current cell in your
DataGridView by using the
CurrentCellAddress property. It returns
the cell coordinates, which are also
called its location or Point. You can
specify X or Y or both.

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.

Example that gets current cell: C#

/// <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.

Example that handles double-clicking: C#

void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)


{
//
// Do something on double click, except when on the header.
//
if (e.RowIndex == -1)
{
return;
}
ProceedOpen();
}

Events in Visual Studio. As a reminder, click on the


DataGridView in the designer. Then look at the Property
pane, which is usually on the right bottom corner. Next
click on the lightning bolt and scroll down to the
CellDoubleClick entry.

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.

Example that uses SelectionChanged: C#

void dataGridView1_SelectionChanged(object sender, EventArgs e)


{
//
www.dotnetperls.com/datagridview-tips 6/11
1/14/14 C# DataGridView Tips
// When our selection changes, call the function SetupButtons
// to make sure "openButton" is always in a valid state.
//
SetupButtons();
}

/// <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);
}

SelectionChanged event handler. The


code uses an event handler. This is
triggered whenever the selection changes in
the DataGridView. This is convenient
because you will want to change the display
when the selection is moved.

The code checks RowCount. When


RowCount is zero, then nothing is selected, and our user
probably can't proceed in your window. This allows us to
disable or enable buttons based on what is selected.

Note:
The user interface will respond instantly when selection
is changed. People love it when programs work better
than expected.

Selection options. The DataGridView has many options


for adjusting its selection features. One option I have used
often is the MultiSelect property. This is described in
another article.
MultiSelect Property: DataGridView

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

need to do a bit of manual tweaking.

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.

Example that improves Vista appearance: C#

public partial class Form1 : Form


{
public Form1()
{
InitializeComponent();
dataGridView1.ColumnHeadersBorderStyle = ProperColumnHeadersBorderStyle;
}

/// <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

You can use this to draw that glyph array image.


Remember to remove the glyph arrow in
ColumnHeaderMouseClick.

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

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy