C# Winforms programatically selecting text in a TextBox not selecting any text

Art Hansen 646 Reputation points
2026-10-21T05:32:58.4333333+00:00

I'm working on a C# Winforms .NetFramework 4.8 app in Visual Studio 2022. I have a TextBox in a Panel ((ArgCodeTBX and UseArgPNL in the code  below) populated programmatically with text from a DataGridView cell in response to a user selecting a row via a CheckBox column. The DataGridView is unbound. The Panel`` is hidden until the user makes a selection at which time the Panel’s Visibility is set to true and the TextBox` is populated.

An example of a cell content's expression is “--window-height=value” and the user must manually replace the word “value” with a valid value. My intent is have all text in the expression after the equal sign preselected for the user.  Here is the relevant code (both attempted flavors are from MSDN:

	if (DGV_Args.Rows[e.RowIndex].Cells[1].Value is bool isChecked && isChecked)
	{
		const int ArgCol = 2;
		string cValue = DGV_Args.Rows[e.RowIndex].Cells[ArgCol].Value.ToString();
		if (cValue.Contains( "=" ))
		{
			var cRect = DGV_Args.GetCellDisplayRectangle( ArgCol, e.RowIndex, true );
			UseArgPNL.Location = new Point(cRect.X + 5, cRect.Y - UseArgPNL.Height);
			UseArgPNL.Visible = true;
			ArgCodeTBX.Text = cValue; // --window-height=value for test
			// try one
			int index = ArgCodeTBX.Text.IndexOf( '=' );
			int argLen = cValue.Length;
			int selLen = argLen - index - 1;
			ArgCodeTBX.Select( index + 1, selLen );
			// try two
			ArgCodeTBX.SelectionStart = cValue.IndexOf( '=' ) + 1;
			ArgCodeTBX.SelectionLength = cValue.Length - cValue.IndexOf( '=' );
		{
	{

This image depict intended vs actual

TBX selecct text

This  is so simple and MSDN so clear that I'm mildly embarrassed to post this but perhaps a freash pair of eyes will see something I'm missing .

Your time & expertise will be appreciated.

Windows development | WinUI
0 comments No comments

2 answers

Sort by: Newest
  1. Gatlin Le (WICLOUD CORPORATION) 1,385 Reputation points Microsoft External Staff Moderator
    2026-10-21T06:58:35.8933333+00:00

    Hi @Art Hansen ,

    Your first Select(index + 1, selLen) call already calculates the correct range. The likely missing step is giving ArgCodeTBX input focus. Select(start, length) selects characters; the parameterless Select() activates the control. With the default HideSelection = true, selected text is not highlighted when the textbox does not have focus. See TextBoxBase.Select and HideSelection.

    Keep your existing checkbox check and panel positioning. Replace the code from UseArgPNL.Visible = true through the two selection attempts with:

    UseArgPNL.Visible = true;
    ArgCodeTBX.Text = cValue;
    
    int equalsIndex = ArgCodeTBX.Text.IndexOf('=');
    if (equalsIndex >= 0)
    {
        ArgCodeTBX.Select(); // Give the textbox input focus first.
    
        int start = equalsIndex + 1;
        ArgCodeTBX.Select(start, ArgCodeTBX.TextLength - start);
    }
    

    In a small WinForms test targeting .NET Framework 4.8, running on .NET Framework 4.8.1, the original range selection returned SelectionStart = 16, SelectionLength = 5, and SelectedText = "value" while no highlight was visible. Adding the parameterless Select() made the textbox focused and the selection visible.

    Local WinForms test: adding Select() focuses the textbox and highlights value; the application reports Start=16, Length=5 and SelectedText='value'.

    If you also want the selection to remain visible when another control receives focus, set ArgCodeTBX.HideSelection = false once in the constructor after InitializeComponent(), or in the Designer. That changes highlight visibility; it does not move keyboard input into the textbox.

    Your second attempt requests one character too many. The correct length is TextLength - SelectionStart. WinForms clamps the extra character at the end of the text, so that arithmetic difference did not explain the missing highlight.

    If the selection disappears again after the grid event finishes, please share which DataGridView event contains this code and whether ArgCodeTBX.Focused is still true and ArgCodeTBX.SelectedText is still "value" at that point. That will help distinguish focus returning to the grid from another handler changing the selection.

    If you found my response helpful or informative, I would greatly appreciate it if you could follow this guidance. It also helps other community members who run into a similar issue find the solution more easily.

    Thank you.

    Was this answer helpful?


  2. HelpfulTech 0 Reputation points
    2026-10-21T06:52:55.66+00:00

    The selection is probably being set but not displayed, because a TextBox hides its selection when it does not have focus. Call ArgCodeTBX.Focus() before calling Select so the control has focus and the highlighted text becomes visible. As an alternative, set ArgCodeTBX.HideSelection to false so the selection stays visible even when the control does not have focus.

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.