Shaiwal Tripathi
Shaiwal Tripathi

Reputation: 526

Can't Focus To Any Control after Closing Dialog

I am showing some database records in a Dialog. When I click any particular record that record fills to Active Form.
But I want to focus to a button when my dialog close. So I have written the following code on form closing evennt.

private void frmDG_RecordSelection_FormClosing(object sender, FormClosingEventArgs e)
{
    RecordSelectionStatus.Text = "False";
    Form TargetForm = Home.ActiveMdiChild;

    Button SelectRefConsultant = (Button)TargetForm.Controls.Find("btnSelectRefConsultant_NI", true).SingleOrDefault();
    SelectRefConsultant.Focus();
    TargetForm.ActiveControl = SelectRefConsultant;                                       
}

But it's not working. Focus still remain to it's previous place. What am I missing ?

Upvotes: 1

Views: 851

Answers (2)

Adam Jachocki
Adam Jachocki

Reputation: 2125

If frmDG_RecordSelection is also MDIChild, then Home.ActiveMDIChild is this form. That is being closed.

But if frmDG is just a Dialog, the problem is different.

This dialog is Closing. But it's still visible. You cannot set focus to control that is not visible. So you will have to set focus after this frmDG is completely closed, and invisible... To be more specific, when your MDI form is visible.

It's far more easier to do this from your MDI Form. I don't know how you have programmmed it, but I suppose it's something like that:

//this is in your MDI form
void OnRecordSelected(...)
{
    frmDG yourDialog = new frmDG();
    frmDG.ShowModal();

    frmDG.Dispose();
}

In this case, you will have to set focus after frmDG is disposed.

Upvotes: 0

Leo
Leo

Reputation: 5122

I am assuming that the dialog is modal... Instead of doing this in FormClosing do it, after calling ShowDialog(). If not, try using the FormClosed event instead.

I think your code is not working because, while the Form is closing, it still has modal focus.

Upvotes: 2

Related Questions