Alison Craig
Alison Craig

Reputation: 95

C# how can I select all the text in a textbox when I double click?

Using C# how can I select all the text in a textbox when I double click? My text contains spaces "This is a test", when I double click by default only one word is highlighted, how can I highlight all the text?

What I am trying to achieve is a quick way for users to clear the texbox of text, the text exceeds the length of the box so you can't select the end and drag back to delete, you have to click and use the backspace and delete keys to clear the text.

Thanks Alison

Upvotes: 8

Views: 22029

Answers (6)

Thomson
Thomson

Reputation: 21625

Triple clicks could select the whole paragraph. If you change the behavior of double click, word selection could be a little hard.

Upvotes: 2

cordellcp3
cordellcp3

Reputation: 3623

try something like this. When the MouseDoubleClick-Event is fired...

myTextBox.SelectAll();

Just check the MSDN --> http://msdn.microsoft.com/en-us/library/system.windows.controls.primitives.textboxbase.selectall.aspx

Upvotes: 4

Gerald Davis
Gerald Davis

Reputation: 4549

The textbox control exposes the SelectionStart and Selection Length properties.

You just need to simply wire the double click event of the textbox to set those properties.

SelectionStart will be 0. SelectionLength will be the length of the text (easily determined by the Text property).

On edit: The above solution to use SelectAll() is much easier.

Upvotes: 1

Chris Baxter
Chris Baxter

Reputation: 16353

Assuming we are talking WindowsForms, then all you have to do is attach an EventHandler to the DoubleClick event and invoke SelectAll

private void sampleTextBox_DoubleClick(object sender, EventArgs e)
{
  sampleTextBox.SelectAll();
}

Upvotes: 1

npinti
npinti

Reputation: 52185

You can attach a DoubleClick event handler to the textbox and then call the SelectAll method

Upvotes: 1

Neil Knight
Neil Knight

Reputation: 48547

TextBox tb = new TextBox();
tb.SelectAll();

The TextBox has a SelectAll method which you can use. Add it in your double click event handler.

Upvotes: 5

Related Questions