取消选择文本框中的文本

Fro*_*roz 13 c#-4.0

我有一个Windows窗体,它将文本框中的text属性设置为字符串变量的属性.运行表单时,它会选中文本框中的所有文本.我需要尝试弄清楚如何防止这种情况发生.我试过了

DeslectAll() 
Run Code Online (Sandbox Code Playgroud)

文本框上的方法,但似乎不起作用.我也试过了

txtBox.SelectNextControl(txtCostSummary, true, false, true, true);
Run Code Online (Sandbox Code Playgroud)

但我有点猜测需要设置什么,调整它们似乎并没有什么不同.为了真正理解我在做什么,我会更清楚地了解这一切是如何发生的.

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
    }
}
Run Code Online (Sandbox Code Playgroud)

一切正常,除了它在文本框中打印信息的部分,但文本框中的所有文本都被选中,这不是我认为会发生的,也不是我想要发生的事情.

谢谢你的任何想法!

Ste*_*Cav 44

试试这个:

txtBox.Select(0, 0);
Run Code Online (Sandbox Code Playgroud)

  • 对不起,我去过这里已经有一段时间了.对不起,我迟到了. (2认同)

Mar*_*ani 13

我知道这是一个老问题,但我发现这也有效:

txtBox.SelectionLength = 0;
Run Code Online (Sandbox Code Playgroud)

这可能比SteveCav更好,Select(0,0)因为它不会移动选择起点.


小智 5

尝试这个:

//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;
Run Code Online (Sandbox Code Playgroud)

  • +1 因为我不知道 TabStop 属性会解决这个问题。 (2认同)