Home
Search
DataGridViewAdd the DataGridView control in Windows Forms. Use DataSource and CurrentCellAddress.
C#
This page was last reviewed on Sep 24, 2022.
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.
Shows a datagridviewShows a datagridview
Intro notes. We show some improvements to usability and appearance for this control. Using an object like a data adapter improves performance.
SqlDataAdapter
DataSource example. You 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.
DataSource
GetSearchResults This method 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.
DataTable
Shows a datagridview
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; }
Objects. Here we use a collection with an implementation of IList. The DataGridView will read the property names of your collection objects automatically.
So We can create a new List or array of objects, and then set the DataSource to this.
IList
List
Example that uses object collection, C#:
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; }
Add rows. 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.
Rows On the rows collection, there is a method called Add. But it is usually better to modify the DataSource.
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.
ValueType Every cell has a ValueType. If you want to specify a DateTime column, you can change it by assigning it to a type, using typeof.
DateTime
Typeof, nameof
Shows a datagridview
Example that adds rows, C#:
/// <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; }
Locate current cell. You can locate the current cell with CurrentCellAddress. This returns the cell coordinates, which are also called its location or Point.
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. // 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-clicks. In the event handler for CellDoubleClick, call a method that handles the item. Note that you must check for when 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(); }
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 We can check for CurrentCellAddress to figure out what was selected and where the selection moved.
SelectionChanged This is triggered whenever the selection changes. You will want to change the display when the selection is moved.
RowCount When RowCount is zero, then nothing is selected, and our user probably can't proceed in the window.
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); }
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
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.
And These are not useful for many kinds of applications. Disable row headers by setting RowHeadersVisible to false.
Tabbing. 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 columns. Visual Studio provides dialogs that allow you to configure the columns. Columns are used as templates for how your DataGridView renders columnar data.
Info They do not actually contain the data, just the rules for rendering it to the screen.
MultiSelect. When you create a new DataGridView, the user can select many cells at once. With MultiSelect, we can disable this feature.
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. Just allow one column to fill up the remainder.
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.
PreviewKeyDown. When your DataGridView handles events such as KeyDown, the PreviewKeyDown event can be used to filter some of these events, preventing incorrect behavior.
PreviewKeyDown
List. It is possible to display any List in your DataGridView. You can convert the List to a DataTable, which can then be displayed in the DataGridView.
Convert List, DataTable
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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Sep 24, 2022 (rewrite).
Home
Changes
© 2007-2023 Sam Allen.