tags:

views:

1021

answers:

4

Good Day,

I am playing with a Silverlight control that has a TextBox and Button. When I click the button (which calls SelectText below), I want to select all the text in the textbox.

Here's my code:

    private void SelectText()
    {
        TextBox tb = this.txtFirstName;
        tb.SelectionStart = 0;
        tb.SelectionLength = 3;
        // tb.Select(0, this.txtFirstName.Text.Trim().Length - 1);
        // tb.SelectAll();
        // tb.Text = String.Empty;
    }

The commented code is what I tried already, but neither is working.

Anyone have suggestions on what I'm doing wrong?

coson

A: 

SelectAll() works -- I've used it more than once. Is something manipulating the text box after this method happens?

BC
No, but I have my controls within a grid, I'm wondering if that matters.
coson
+2  A: 

You might need to give focus to the textbox to see the actual selection happening (either before or after selecting, it might not matter but you'll have to try):

private void SelectText()
    {
        TextBox tb = this.txtFirstName;
        tb.SelectionStart = 0;
        tb.SelectionLength = 3;
        // tb.Select(0, this.txtFirstName.Text.Trim().Length - 1);
        // tb.SelectAll();
        // tb.Text = String.Empty;
        tb.Focus();
    }
Denis Troller
That's exactly what I needed!! thanks
coson
A: 

The focus solution worked for me, but sometimes I get this ExecutionEngineException during the SelectAll() and it's totally bogus! Even a try...catch won't stop it and there's no more details about the error.

A: 

I am using Silverlight 3.0 to highlight text in a TextBox. No matter what I do the text of the TextBox it is never highlighted before runtime. When I run the debugger, I see The TextBox text has the property SelectedText equal to the value I set but it won't highlight it. The Focus() does not work either. The question is how do I select text from a TextBox in silverlight 3.0 dynamically?

Leo