Mircea Ispas
Mircea Ispas

Reputation: 20800

Programatically change focus for TextBox in C#

I have a class derived from TextBox in C#. I override OnClick method to show a file open dialog. Is it possible to lose focus after that? I don't want the user to be able to edit the text because at a moment the file name might be invalid. I tried to set ReadOnly = true, but one can change the text after selecting the file.

EDIT:

I added the relevant code for this. As it is now the focus will be set to next control from my Form.

class Property : TextBox
class FileSelectTextBox : Property
{
    protected override void OnClick(EventArgs e)
    {
        OpenFileDialog dialog = new OpenFileDialog();
        Enabled = false;
        if (dialog.ShowDialog(this) == DialogResult.OK)
        {
            Text = dialog.FileName;
        }
        Enabled = true;
    }
}

Upvotes: 0

Views: 1439

Answers (2)

techBeginner
techBeginner

Reputation: 3850

set the ReadOnly = true property of the textbox (don't change it at any point of time) and it should work lonely..

and rest of the code goes like this..

    protected override void OnClick(EventArgs e)
        OpenFileDialog dialog = new OpenFileDialog();

        //user can still change/edit some non-existing file/path and click OK, so set the followings
        dialog.CheckFileExists = true;
        dialog.CheckPathExists = true;

        if (dialog.ShowDialog(this) == DialogResult.OK)
        {
            Text= dialog.FileName;
        }
    }

Upvotes: 0

ean5533
ean5533

Reputation: 8994

You have several options here:

  1. Make the textbox ReadOnly. The textbox will still fire OnClick events but the text won't be editable by the user.
  2. Disable the textbox at the end of your click event -- the disadvantage is that the click event won't fire a second time (which means the user won't be able to change their mind and pick a new file).
  3. Simply set the focus somewhere else at the end of the click event. (someOtherTextBox.Focus())

Edit: Once last suggestion: you may want your file popup to happen in FocusGained rather than OnClick, that way the dialog will still pop up if the user tabs into the control. Of course it's your decision if that behavior is desired or not.

Edit 2: Ignore that last edit. It's a bad suggestion that I didn't think through. (Thanks for the heads up commenter)

Upvotes: 1

Related Questions