Matt Chambers
Matt Chambers

Reputation: 2346

Why does ShowDialog select text in my TextBox?

I have a very simple error popup I'm trying to make. When I call ShowDialog, all the text in the textbox gets selected. It looks silly. When I break right before ShowDialog, no text is selected. After the call to ShowDialog, all the text is selected without any user interaction.

    static void ShowError(string error)
    {
        var form = new Form
        {
            Text = "Unexpected Error",
            Size = new System.Drawing.Size(800, 600),
            StartPosition = FormStartPosition.CenterParent,
            ShowIcon = false,
            MinimizeBox = false,
            MaximizeBox = false
        };

        var textBox = new TextBox
        {
            Text = error,
            Dock = DockStyle.Fill,
            Multiline = true,
            ReadOnly = true,
        };

        form.Controls.Add(textBox);
        form.ShowDialog();
    }

Upvotes: 2

Views: 1231

Answers (3)

Steve
Steve

Reputation: 216293

Well, if you set TabStop=false; the control will be deselected. However, ReadOnly means that your user could always select text manually.

FROM MSDN - . With the property set to true, users can still scroll and highlight text in a text box without allowing changes.

Upvotes: 2

to StackOverflow
to StackOverflow

Reputation: 124696

Try setting SelectionStart explicitly, though I'm not sure why this is necessary:

static void ShowError(string error)
{
    var form = new Form
    {
        Text = "Unexpected Error",
        Size = new System.Drawing.Size(800, 600),
        StartPosition = FormStartPosition.CenterParent,
        ShowIcon = false,
        MinimizeBox = false,
        MaximizeBox = false
    };

    form.SuspendLayout();
    var textBox = new TextBox
    {
        Text = error,
        Name = "textBox1",
        Dock = DockStyle.Fill,
        Multiline = true,
        ReadOnly = true,
        SelectionStart = 0, // or = error.Length if you prefer
    };

    form.Controls.Add(textBox);
    form.ResumeLayout();
    form.PerformLayout();
    form.ShowDialog();
} 

Upvotes: 0

L.B
L.B

Reputation: 116108

You can add SelectionStart=0, SelectionLength = 0 or Enabled = false to your textBox creation code

Upvotes: 3

Related Questions