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;
}
}
You have several options here:
ReadOnly. The textbox will still fireOnClickevents but the text won’t be editable by the user.someOtherTextBox.Focus())Edit: Once last suggestion: you may want your file popup to happen inFocusGainedrather thanOnClick, 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)