Auto highlight text in a textbox control

2019-01-08 20:14发布

How do you auto highlight text in a textbox control when the control gains focus.

标签: c# textbox
15条回答
你好瞎i
2楼-- · 2019-01-08 20:52

You can use this, pithy. :D

TextBox1.Focus();    
TextBox1.Select(0, TextBox1.Text.Length);
查看更多
孤傲高冷的网名
3楼-- · 2019-01-08 20:54

In asp.net:

textBox.Attributes.Add("onfocus","this.select();");
查看更多
Ridiculous、
4楼-- · 2019-01-08 20:54

If your intention is to get the text in the textbox highlighted on a mouse click you can make it simple by adding:

this.textBox1.Click += new System.EventHandler(textBox1_Click);

in:

partial class Form1
{
    private void InitializeComponent()
    {

    }
}

where textBox1 is the name of the relevant textbox located in Form1

And then create the method definition:

void textBox1_Click(object sender, System.EventArgs e)
{
    textBox1.SelectAll();
}

in:

public partial class Form1 : Form
{

}
查看更多
ゆ 、 Hurt°
5楼-- · 2019-01-08 21:02
textbox.Focus();
textbox.SelectionStart = 0;
textbox.SelectionLength = textbox.Text.Length;
查看更多
叼着烟拽天下
6楼-- · 2019-01-08 21:03

If you wanted to only select all the text when the user first clicks in the box, and then let them click in the middle of the text if they want, this is the code I ended up using.

Just handling the FocusEnter event doesn't work, because the Click event comes afterwards, and overrides the selection if you SelectAll() in the Focus event.

private bool isFirstTimeEntering;
private void textBox_Enter(object sender, EventArgs e)
{
    isFirstTimeEntering = true;
}

private void textBox_Click(object sender, EventArgs e)
{
    switch (isFirstTimeEntering)
    {
        case true:
            isFirstTimeEntering = false;
            break;
        case false:
            return;
    }

    textBox.SelectAll();
    textBox.SelectionStart = 0;
    textBox.SelectionLength = textBox.Text.Length;
}
查看更多
神经病院院长
7楼-- · 2019-01-08 21:05

In Windows Forms and WPF:

textbox.SelectionStart = 0;
textbox.SelectionLength = textbox.Text.Length;
查看更多
登录 后发表回答