Search code examples
c#.netformswinforms

How to select a part of the text of a DataGridView cell in c# with Windows Forms?


I'm working on a C# project with Windows Forms and I'm having trouble with a problem that's taking up a lot of my time. The problem is that I want to be able to select only part of the text in a cell that is supposed to be readonly, in order to perform actions on it. For a small example, in Microsoft Access, it's possible to select part of a text without modifying it: example microsoft access I tried a lot of things such as to catch the event CellBeginEdit, etc..., with no results.

Thank you for your help !


Solution

  • allowing text selection in a readonly cell for the purpose of copying or performing other actions on the selected text is not directly supported as a built-in feature. But, you can achieve this functionality through a workaround.

    You can use a TextBox as an overlay and allow text selection.

    private TextBox readOnlyTextBoxOverlay;
    
    public YourFormConstructor()
    {
        InitializeComponent();
        InitializeReadOnlyTextBoxOverlay();
    }
    
    private void InitializeReadOnlyTextBoxOverlay()
    {
        readOnlyTextBoxOverlay = new TextBox
        {
            ReadOnly = true,
            Multiline = true,
            Visible = false,
            BorderStyle = BorderStyle.None
        };
        this.Controls.Add(readOnlyTextBoxOverlay);
        readOnlyTextBoxOverlay.BringToFront();
        readOnlyTextBoxOverlay.Leave += (s, e) => readOnlyTextBoxOverlay.Visible = false;
    }
    
    private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
    {
        if (e.RowIndex >= 0 && e.ColumnIndex >= 0) // Check if the click is on a valid cell
        {
            Rectangle cellRect = dataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, false);
    
            readOnlyTextBoxOverlay.Location = cellRect.Location;
            readOnlyTextBoxOverlay.Size = cellRect.Size;
            readOnlyTextBoxOverlay.Text = dataGridView1[e.ColumnIndex, e.RowIndex].Value?.ToString();
            readOnlyTextBoxOverlay.Visible = true;
            readOnlyTextBoxOverlay.Focus();
            readOnlyTextBoxOverlay.SelectAll();
        }
    }
    
    private void dataGridView1_CellLeave(object sender, DataGridViewCellEventArgs e)
    {
        readOnlyTextBoxOverlay.Visible = false;
    }
    

    The textBox is initialy hidden because it will only be visible once you clicked the cell you want to "edit" select something for copying or something