Search code examples
c#showdialog

replacing show() with showdialog()


I am opening a form at run time from the main gui form using form.showdialog();

I set the proppeties likeform should appear in center etc

 form.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
form.ClientSize = new System.Drawing.Size(200, 50);
form.StartPosition = FormStartPosition.CenterParent;

and added a label

Label popupLabel1 = new Label();
form.Controls.Add(popupLabel1);

Problem is when i replace form.showdialog() with form.show() I cant see the content of label and now this new form does not appear in the center. Why these set properties are not occuring ?

Thanls


Solution

  • You aren't showing your full code, which is necessary in the case. When and where is what code executed?

    What you need to remember is that .Show() is not a blocking call, while .ShowDialog() is a blocking call. This means that if you have code after the .Show/ShowDialog call, this won't be executed immediately when you use ShowDialog - it will be executed when the form is closed.

    Assuming you have code like this:

    var form = new YourForm();
    form.Show(); // NOT BLOCKING!
    form.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
    form.ClientSize = new System.Drawing.Size(200, 50);
    form.StartPosition = FormStartPosition.CenterParent;
    Label popupLabel1 = new Label();
    form.Controls.Add(popupLabel1);
    

    If you change the Show to ShowDialog, then you need to move it to the end, after the creation of the labels.

    var form = new YourForm();
    form.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
    form.ClientSize = new System.Drawing.Size(200, 50);
    form.StartPosition = FormStartPosition.CenterParent;
    Label popupLabel1 = new Label();
    form.Controls.Add(popupLabel1);
    form.ShowDialog(); // BLOCKING!