How do I highlight a selection made programmatically in a Winforms TextBox
Question
I've not gone into much research here, but the intuitive thing is not working:
private void SerachButton1_Click(object sender, EventArgs e)
{
String serchTerm = searchTerm1.Text;
String text = usualTextBox.Text;
Int32 index = text.IndexOf(serchTerm);
if (index >= 0)
{
usualTextBox.Select(index, serchTerm.Length);
}
}
SelectedText
, SelectionLength
and SelectionStart
properties are as I expect them after Select
is called but there's no visible selection.
What am I doing wrong here?
Edit: I've also tried RichTextBox
. When I set background and text colors for the selection it shows up, but it won't unselect automatically when you manually select another part of text or just click on a position in text. Are these two types of selection inherently different and if you select programmatically you have to also deselect programmatically?
Solution
You need to set usualTextBox.HideSelection
to false
so that the selection remains visible when the focus is not in the TextBox
.