How do you keep the text selection on a DataGridView?

Posted by fneep on Stack Overflow See other posts from Stack Overflow or by fneep
Published on 2010-04-11T09:32:38Z Indexed on 2010/04/11 9:33 UTC
Read the original article Hit count: 377

Filed under:
|
|
|

I'm running C# 2.0, and I've written an application with a DataGridView in virtualmode and a TreeView in the same form, but in different panels of a SplitContainer.

My application has a "find all" function that finds all instances of a certain string, and adds them as the child nodes to a new node to the TreeView (it's a tree view because you can have multiple search results by having different root nodes).

That idea is that when you click on one of those search results in the TreeView, that it would select the specific text of that result in the DataGridView (Virtually the same as Notepad++'s find all function)

When I click on the TreeView, it does set the selected cell of the DataGridView and highlight the specific text, but it loses that specific text selection instantly (but keeps the cell selection) because by clicking on the TreeView the DataGridView loses focus.

Here's the code for the AfterSelect of the TreeView:

   private void Tree_Results_AfterSelect(object sender, TreeViewEventArgs e)
   {
       if (e.Node.Level > 0)
        {
            SearchResult SelectedItem = (SearchResult)Tree_Results.SelectedNode.Tag;
            DataViewMain.CurrentCell = DataViewMain[SelectedItem.TypeIndex, SelectedItem.LineIndex];
            DataViewMain.BeginEdit(false);
            DataGridViewTextBoxEditingControl SelectionData = (DataGridViewTextBoxEditingControl)DataViewMain.EditingControl;
            SelectionData.SelectionStart = SelectedItem.HighlightStart;
            SelectionData.SelectionLength = SelectedItem.HightlightLength;
        }
    }

If the DataGridView were a text box I could possibly set HideSelection to false, but DataGridViews have no such property (and changing the Hide Selection for the EditingControl does nothing)

Any ideas? I'm receptive to a different control instead of a TreeView that would allow my DataGridView to retain focus.

© Stack Overflow or respective owner

Related posts about c#

Related posts about datagridview