Zee99
Zee99

Reputation: 1234

open a modal form from my usercontrol

I have a usercontrol that opens a form. i want this form to open as modal having its parent the same parent of the usercontrol. is that possible? (all i need is that the form is open modal).

when i tried (form.parent = this.parent) i got an error saying the form is a toplevel form. then i tried (form.toplevel=false; form.parent=this.parent) and here i got a cross-thread operation error.

thanks for helping.


Hans, here are parts of my code, thanks.

private void Container_DragDrop(object sender, DragEventArgs args)   
{

         ThreadPool.QueueUserWorkItem(
                delegate(object state)
                {

                    object[] parameters = (object[])state;
                    object s = parameters[0];
                    DragEventArgs e = parameters[1] as DragEventArgs;
                    this.OnContainerDragandDrop(s, e);

                },
                new object[] { sender, args });
}

private void OnContainerDragandDrop(object sender, DragEventArgs e)
    {
    //here I am calling a method
    MyMethod(e)
    }

private void MyMethod(DragEventArgs e)
{
mywcfClient.MyrequestWasSuccessfull += new MyRequestInfoEventHandler(mywcfClient_MyrequestWasSuccessfull);
}

void  mywcfClient_MyrequestWasSuccessfull (object sender, MyRequestInfoEventargs args)
{

//this is where I wanna show my form
From frm = new Form();
Frm.showdialog() //here the form is showing but non modal, i want to show it as modal}

Upvotes: 0

Views: 1745

Answers (1)

Hans Passant
Hans Passant

Reputation: 942197

It's a bit hum to have a user control open a form, consider raising an event so that the control's parent form stays in control and displays the dialog.

But okay if the dialog is a complete implementation detail of the control. Don't set the Parent, you need to use the ShowDialog(owner) overload if you want to pick a specific owner. It isn't typically necessary, the ShowDialog() method goes hunting for a suitable owner if you don't specify one. You can find the parent form of the control back with code like this:

    private Form GetParentForm() {
        var parent = this.Parent;
        while (!(parent is Form)) parent = parent.Parent;
        return parent as Form;
    }

But you've got another problem, also the reason why you asked this question in the first place. Your dialog right now doesn't have an owner and it is likely to disappear behind another window. That's because your code runs on another thread. A thread that created no windows, and thus can't supply an owner window, and the reason for the cross-thread exception message.

You need to use Control.Invoke to run the dialog code on the UI thread. There's a good example of it in the MSDN Library topic for it.

Upvotes: 1

Related Questions