C# DataGridView

DataGridView example

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

Programming tip

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;
}
This section provides information

After BuildDataGrid is called, the above code sets the 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

SQL: Structured Query Language

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.

DataGridView screenshot
Example that uses object collection: C#

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

DataGridView screenshot

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.

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

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.

Value

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

DateTime ExamplesTypeof 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.
    //
    int yCoord = dataGridView1.CurrentCellAddress.Y; // You can get X if you need it.
    DateTime thisDate = (DateTime)dataGridView1.Rows[yCoord].Cells[1].Value;
}

Double-clicks

Lightning bolt

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

Note

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

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 need to do a bit of manual tweaking.

Alternating colors

Programming tip

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;
	}
    }
}
DataGridView example

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 programming language

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.

Framework: NET

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

List type

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

Steps

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.

DataGrid

Summary

C# programming language

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.


C#: Windows