Resolved How to allow selecting parts of text inside a ReadOnly DataGridViewTextBoxColumn

Godfrey

New member
Joined
Dec 17, 2023
Messages
4
Programming Experience
10+
Default behavior is whole cell gets selected. I need user to be able to select part of text, and then use the selected part in context menu event handlers. What complicates things even more is that the only method I know of to get selected part of a cell's text is to get underlying control, something like TextBox tb = (TextBox)myDataGridView.EditingControl; string txt = tb.SelectedText; however ReadOnly cells have no EditingControl (I think, haven't tested yet).

I guess I could create myself a special type of DataGridViewColumn that looks and acts as if it's ReadOnly i.e. cell's graphics does not change at all when in edit mode, no cursor appears and (somehow) does not allow user change text only select it. Looks a bit complicated but probably doable. Or is there a better way? Maybe there's already something like that, or a third party library for this?
 
Last edited:
I don't know the answer to your question but, on the subject of editing controls, no cells contain an editing control by default, whether read-only or not. That's how a DataGridView control is able to be efficient. An editing control is only created or reused when you start an editing session on a cell. You can't start an editing session on a read-only cell, so they never have an editing control.

One solution could be to not make the column or its cells read-only and to handle the EditingControlShowing event and, for that column, cast the editing control as type TextBox and set its ReadOnly property to true. As far as the grid was concerned, the user would be editing the cell but they'd never be able to change the text it contains. The user can still select and copy text from a read-only TextBox.

If you wanted to be able to do it otherwise then I suspect that it would involve Windows messages.
 
One solution could be to not make the column or its cells read-only and to handle the EditingControlShowing event and, for that column, cast the editing control as type TextBox and set its ReadOnly property to true. As far as the grid was concerned, the user would be editing the cell but they'd never be able to change the text it contains. The user can still select and copy text from a read-only TextBox.

Great idea, exactly what I needed. Thanks a bunch :)
 

Latest posts

Back
Top Bottom