Switch On The Code RSS Button - Click to Subscribe
May
2

C# Snippet Tutorial - Modify a Cell’s Selected Text

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. If you've got any comments or questions, just post them below.



Posted in C#, All Tutorials by The Reddest |

2 Responses

  1. dudeman Says:

    so you are getting an editingcontrol from _myDataGrid, which i assume is a cell. But a grid can have many cells (columns, rows) how do you know which cell do you have. I didn’t see you specify the row or column any where in this sample. I am confused.

  2. The Reddest Says:

    _myDataGrid is the actual DataGridView. The EditingControl is the control located inside the currently selected cell. I’m relying on the user to select the cell, instead of me explicitly setting it. You can change the currently selected cell by using the CurrentCell property on the DataGridView if you want to modify the text in a cell that is not already selected.

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.

Powered by WP Hashcash