23

I have a windows form that sets the text property in a textbox to that of a string variable. When the form is ran, it has all of the text in the textbox selected. I need to try and figure out how to keep that from happening. I tried the

DeslectAll() 

method on the textbox but that doesn't seem to work. I also tried

txtBox.SelectNextControl(txtCostSummary, true, false, true, true);

but I kind of was guessing on what the paramters needed to be set to, tweaking them doesn't seem to make a difference. To really understand what I'm doing I'll make it a little more clear on how this all is happening.

public Form1()
{
    Apple a = new Apple();
    a.IwantThisText = "Item 1: " + 50.00 + "\r\n";
    txtBox.Text = a.IwantThisText;
}

Class Apple
{
    private string iWantThisText;
    public string IwantThisText
    {
    get { return iWantThisText; }
    set { iWantThisText += value; } // Appends what was there before
    }
}

Everything works fine except the part where it has printed the information in the textbox but all the text in the textbox is selected, which isn't what I thought would happen, nor is it what I want to happen.

Thanks for any ideas!

Froz
  • 233
  • 1
  • 2
  • 4

3 Answers3

64

Try this:

txtBox.Select(0, 0);
Himanshu
  • 31,810
  • 31
  • 111
  • 133
SteveCav
  • 6,649
  • 1
  • 50
  • 52
  • 3
    Sorry, been a while since I've been on here heh. Sorry for the super late answer. – Froz Apr 28 '13 at 14:04
19

I know it's an old question, but I found that this works too:

txtBox.SelectionLength = 0;

This might be preferable to @SteveCav's Select(0,0) as it doesn't move the selection start point.

Marcello Romani
  • 2,967
  • 31
  • 40
10

Try this:

//remove focus from control.
Apple a = new Apple();    
a.IwantThisText = "Item 1: " + 50.00 + "\r\n";    
txtBox.Text = a.IwantThisText;

// Add this
txtBox.TabStop = false;
DarthJDG
  • 16,511
  • 11
  • 49
  • 56
Vijay
  • 101
  • 1
  • 2