Customizing DataGridView
You can customize the DataGridView to work the way you want. There are scenarios when default behavior of the DataGridView is not sufficient to fulfill the requirements. For example you want to override the behavior of DataGridView such that when i press enter key on a particular cell the cursor/focus move to the cell below to that cell not in the next cell (which is default behavior) similarly while editing data in DataGridView you don't want that the cursor move to the first cell of the next row after editing a row however you want to skip the first column for editing e.g there is an row counter in the first column and you don't want to edit it.
So lets dig into customizing the DataGridView and make it the way we want....
In this sample we modify the DataGridView Behavior as follows; On pressing enter on any cell it creates the new DataGridView row below to that cell and when tab button is pressed at the last cell of the row it creates the new row and moves the cursor to the second cell of the new row (skipping the first column).
In order to customize the DataGrid, we would have to create a new Component which will directly inherit from the DataGridView as;
public partial class myDGView : DataGridView
and we will required to override the following two methods;
-
protected override bool ProcessDialogKey(Keys keyData)
This method is called during message preprocessing to handle dialog characters, such as TAB, RETURN, ESCAPE, and arrow keys.
-
protected override bool ProcessDataGridViewKey(KeyEventArgs e)
Processes keys used for navigating in the DataGridView
In both of the above methods; we do much the same thing. We check which key has been pressed and then respond accordingly;
The below code snippets checks the key pressed and then adds the new row below the current row
if (keyData == Keys.Enter)
{
base.Rows.Insert(base.CurrentRow.Index + 1, 1);
base.SelectedCells[0].Selected = false;
base.Rows[base.CurrentRow.Index + 1 + 1].Cells[1].Selected = true;
base.CurrentCell = base.Rows[base.CurrentRow.Index + 1 ].Cells[1];
return true;
}
The source code is attached which contains the C# Library Project sample code. Which will generate the DLL which you can add in your Visual Studio's Toolbox by just drag & drop and can use the customized DataGridView as an simple DataGridView.
1 Comment
Comments have been disabled for this content.
Nguyen Dinh Hung said
it worked for me ;) thank u!