Determine Text Selected in a DataGridView Cell

Posted on 2007-03-29
Last Modified: 2013-11-26
I need to determine which text the user selected in a DataGridView cell.

For example, if the current cell value is "This is a Test" and the user selects the word Test, I need to get the word Test.
Question by:Kramarich
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
LVL 34

Expert Comment

ID: 18820662
Can you please say a bit more about the context in which "if the current cell value is "This is a Test" and the user selects the word Test, I need to get the word Test"?

The reason for my question is this.  If the user right clicks on the cell when the word Test is selected then the context menu will allow the selected text to be copied to the Clipboard.  So, in that context, the facility is already available.  If we change the context, then there are all sorts of issues that arise.  For instance, the selectedtext is "selected" not in the cell itself but in the DataGridViewTextBoxEditingControl which replaces the cell itself during an edit operation.  And although it is available from that, whether that is available depends on when and how you want to get hold of the word.


Author Comment

ID: 18822904
I need to capture the word(s) the user has selected (highlighted) in the cell programatically.  I want the user to be able select a word or words in a cell and then press another button which will start a search for the selected word(s) and display the results.   So I need to capture what the user selected.

The DataGridViewTextBoxEditingControl looks like it has the property I want to use (DataGridViewTextBoxEditingControl.SelctedText) but I can't figure out how implement this.

LVL 34

Accepted Solution

Sancler earned 250 total points
ID: 18824904
The DataGridViewTextBoxEditingControl looks like it has the property I want to use (DataGridViewTextBoxEditingControl.SelctedText) but I can't figure out how implement this.

Yes, that's the problem ;-).  Because it is an EditingControl it ceases to be accessible as soon as the user stops editing the cell.  Here's a demo of a workaround.  One form, one datagridview - called dgv - one button.  This code

Public Class frmGetSelText

    Private dt As New DataTable("DummyTable")
    Private myTextBox As System.Windows.Forms.DataGridViewTextBoxEditingControl
    Private mySelectedText As String

    Private Sub filltable()
        Dim dc0 As New DataColumn("ID", GetType(Integer))
        Dim dc1 As New DataColumn("Name", GetType(String))
        Dim dc2 As New DataColumn("Item", GetType(String))
        Dim dc3 As New DataColumn("Description", GetType(String))
        For i As Integer = 1 To 5
            Dim dr As DataRow = dt.NewRow
            dr(0) = i
            dr(1) = "Name" & i.ToString
            dr(2) = "Item" & i.ToString
            dr(3) = "Description" & i.ToString
    End Sub

    Private Sub frmGetSelText_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        dgv.DataSource = dt
    End Sub

    Private Sub dgv_CellLeave(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgv.CellLeave
        If Not myTextBox Is Nothing Then
            mySelectedText = myTextBox.SelectedText
        End If
    End Sub

    Private Sub dgv_EditingControlShowing(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles dgv.EditingControlShowing
        If dgv.CurrentCell.ColumnIndex = 3 Then
            If TypeOf (e.Control) Is System.Windows.Forms.DataGridViewTextBoxEditingControl Then
                myTextBox = e.Control
            End If
            myTextBox = Nothing
        End If
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    End Sub
End Class

It works with some dummy data, and is organised at the moment (although you could change that) so that only one column - the "Description" column, index 3 - provides the facility you want.  If you select some text in a record in that column, that will remain available in mySelectedText until something different is selected in a record in that column.  It is, as presented here, very rudimentary.  But it illustrates one way of getting hold of, and keeping, what otherwise ceases to be available once focus has moved off a cell that was being edited.


Author Comment

ID: 18828949
Thanks Roger!  With your sample code I was able to do what I needed.  However, I had to change a couple of things.  For some reason, when I went to use mySelectedText in the Button1_click event, the value in mySelectedText would be the value of cell (0,0) instead of the word I had selected from another cell.  I walked through the execution and the value of mySelectedText seemed to be getting set correctly but I just couldn't figure out how it was getting reset to the cell(0,0) value when I pressed Button1.

I got around the problem by doing the following:
  Eliminatied the dgv_CellLeave event.
  Eliminated the mySelectedText variable.
  In the Button1_Click event, used myTextBox.SelectedText instead of mySelectedText.

Thanks again for your help.  I'll accept your solution.
LVL 34

Expert Comment

ID: 18828991

I'm not sure why that was happening.  I've just gone back to the test program and couldn't make it happen that way.  But It doesn't really surprise me.  So much depends on the details of the data and the binding set up and settings on other properties so far as where focus goes is concerned.  And it sounds as though, somewhere along the line, focus was going back - undirected and unnoticed and probably momentarily - to cell 0,0.  Still, you sorted it.  Good.


Featured Post

Quiz: What Do These Organizations Have In Common?

Hint: Their teams ended up taking quizzes, too.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Creating an analog clock UserControl seems fairly straight forward.  It is, after all, essentially just a circle with several lines in it!  Two common approaches for rendering an analog clock typically involve either manually calculating points with…
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
Monitoring a network: how to monitor network services and why? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the philosophy behind service monitoring and why a handshake validation is critical in network monitoring. Software utilized …
Do you want to know how to make a graph with Microsoft Access? First, create a query with the data for the chart. Then make a blank form and add a chart control. This video also shows how to change what data is displayed on the graph as well as form…

630 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question