DataGridView
This Windows Forms control displays the contents of a data source. It uses a grid format. There are many ways to improve its default configuration.
We show some improvements to usability and appearance for this control. Using an object like a data adapter improves performance.
DataSource
exampleYou can use the DataSource
property to hook your DataGridView
up to a database or an object collection. The code sets DataSource
to the results of GetSearchResults
.
GetSearchResults()
method performs a custom search. This is custom code that will query a database for results.DataTable
. We can use an SqlDataAdapter
to fill this DataTable
object. The results appear in your DataGridView
./// <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; }
Here we use a collection with an implementation of IList
. The DataGridView
will read the property names of your collection objects automatically.
List
or array of objects, and then set the DataSource
to this.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;
}
You can add rows to the DataGridView
by using the Add method in C# code. This method adds a row to the DataGridView
—it returns the added index.
DataSource
.ValueType
. If you want to specify a DateTime
column, you can change it by assigning it to a type, using typeof
./// <summary> /// Shows example usage of Add method on Rows. /// </summary> void M() { // // 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; }
You can locate the current cell with CurrentCellAddress
. This returns the cell coordinates, which are also called its location or Point
.
/// <summary> /// Shows example usage of how to get the current cell. /// </summary> void M() { // // Go from Y coordinate to a selected cell's value. // The Cells[1] part 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
-clicksIn the event handler for CellDoubleClick
, call a method that handles the item. Note that you must check for when RowIndex
equals -1.
RowIndex
is -1, it indicates that the column headers were double
-clicked and not a regular cell.void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
//
// Do something on double click, except when on the header.
//
if (e.RowIndex == -1)
{
return;
}
ProceedOpen();
}
SelectionChanged
You can update your program's buttons when the user selects a cell. We listen for SelectionChanged
and change controls based on the selection.
CurrentCellAddress
to figure out what was selected and where the selection moved.RowCount
is zero, then nothing is selected, and our user probably can't proceed in the window.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); }
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
.
Hide row headers by using the RowHeadersVisible
property. When you create a new DataGridView
, there will be ugly row headers with arrows in the left column.
RowHeadersVisible
to false.Use StandardTab
in the designer to make the tab key move out of the DataGridView
and to the next control. The tabbing events won't get stuck in the DataGridView
.
Configure
columnsVisual Studio provides dialogs that allow you to configure the columns. Columns are used as templates for how your DataGridView
renders columnar data.
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.
PreviewKeyDown
When your DataGridView
handles events such as KeyDown
, the PreviewKeyDown
event can be used to filter some of these events, preventing incorrect behavior.
We improved the usability and appearance of the DataGridView
in a program with these methods. DataGridView
is ideal in .NET for viewing information from databases or object collections.