0

I'm trying to make it in my program, if you click on a text box it will select it all. And then if you click it again it deselects it all.

I've tried making it like this..

 private void url_MouseDown(object sender, MouseEventArgs e)
    {
        url.ReadOnly = false;
        url.SelectAll();
        url.DeselectAll();

    }

I know the url.DeselectAll(); is in the wrong spot. Any help? Thanks in advance!

user2178586
  • 141
  • 2
  • 3
  • 9
  • 1
    What type is "my program"? Asp.net webforms? – speti43 Mar 19 '13 at 16:22
  • You have your answer right in front of you, the key word `Click` should lead you to which `Event` to put your code. Here is a hint.. if Clicked Keep a `Counter or Boolean`, then `SelectAll` method will be Invoked.. if Clicked again, Check if Clicked is True then InVoke `DeselectAll` Method() and set Boolean back to False does this make sense – MethodMan Mar 19 '13 at 16:22

3 Answers3

0

Your current code first calls

url.SelectAll();

and then immediately calls

url.DeselectAll();

Instead, check the current state of the item you are trying to toggle. It's not clear to me from the question exactly what that is, so in pseudocode:

private bool isSelected = false;

private void url_MouseDown(object sender, MouseEventArgs e)
{
    url.ReadOnly = false;
    if (isSelected)
    {
        url.DeselectAll();
    } 
    else 
    {
        url.SelectAll();
    }
    isSelected = !isSelected;
}

Replace IsDeselected with something that checks whether the current state is deselected or not.

Eric J.
  • 147,927
  • 63
  • 340
  • 553
  • Updated for the case that only the MouseDown event causes selection to toggle. Assumes initial state is not selected. – Eric J. Mar 19 '13 at 21:31
0

Clicking the textbox itself clears a selection, so you'd have to do something like this;

    bool selected;
    private void url_MouseDown(object sender, MouseEventArgs e)
    {
        url.ReadOnly = false;
        if (!selected)
        {
            selected = true;
            url.SelectAll();
        }

        else
        {
            selected = false;
            url.DeselectAll();
        }
    }
stevepkr84
  • 1,637
  • 2
  • 13
  • 23
0

Your code always selects and then deselects again, so your text will always be deselected after mouse down.

Try this instead:

private void url_MouseDown(object sender, MouseEventArgs e)
{
    url.ReadOnly = false;
    if (url.SelectedText.Length < url.Text.Length) {
        url.SelectAll();
    } else {
        url.DeselectAll();
    }
}
Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188