C# Snippet Tutorial - Modify a Cell's Selected Text [Beginner]


In this short tutorial, I'm going to show you how to change the text selection in a DataGridViewCell. There's lots of reasons why someone would want to do this, like if someone enters something incorrectly, maybe you want to select all the text so they can enter something else.

The easiest want to select all the text in a cell is call BeginEdit on the DataGridView. The BeginEdit function takes a parameter that tells it whether or not to select all the text in the cell.
_myDataGrid.BeginEdit(true);
 
This is great, except when you want to select text while you're already in edit mode. This can be accomplished by actually getting a hold of the edit control and working directly with it. The DataGridView exposes the control through the property, EditingControl. Depending on what type of column the cell is in, the EditingControl could be many different types. For this tutorial, I'm going to assume we're using the standard DataGridViewTextBoxColumn, which will give us a DataGridViewTextBoxEditingControl. Boy, .NET has some long names.
DataGridViewTextBoxEditingControl editControl =
    (DataGridViewTextBoxEditingControl)_myDataGrid.EditingControl;
 
If the DataGridView doesn't have a cell in edit mode, the EditingControl will be null, so you might want to check for that before casting it. Now to set the text selection, we can do it like we would any regular TextBox.
DataGridViewTextBoxEditingControl editControl =
    (DataGridViewTextBoxEditingControl)_myDataGrid.EditingControl;

//selects to the first two characters
editControl.SelectionStart = 0;
editControl.SelectionLength = 2;

//selects all the text
editControl.SelectionStart = 0;
editControl.SelectionLength = editControl.Text.Length;
 
Just like with a TextBox, you can set the SelectionStart and SelectionLength properties to change the cell's selected text. I think that just about does it for this snippet tutorial.

Comments