Click here to Skip to main content
11,806,931 members (64,303 online)
Rate this: bad
Please Sign up or sign in to vote.
See more: C#
On button click event in windows form I use following code to show page setup dialog.
PageSetupDialog pageSetup = new PageSetupDialog();
pageSetup.PrinterSettings = new System.Drawing.Printing.PrinterSettings();
pageSetup.PageSettings = new System.Drawing.Printing.PageSettings();
pageSetup.EnableMetric = false;

After setting page setup and printer I clicked Ok. But when page setup dialog opens again it is reseted to the default settings. Previously changed values not displayed.
Posted 25-Dec-11 16:02pm
Rate this: bad
Please Sign up or sign in to vote.

Solution 1

You are NOT saving any settings. There basically are two ways to get previous values as preset defaults:

1. keep using the same dialog, i.e. move the new PageSetupDialog(); line out of the loop.

2. or actually do save the settings, then restore them to your next dialog when you need it.

Obviously #1 is the easier way.

Smile | :)
Rate this: bad
Please Sign up or sign in to vote.

Solution 2

Of course it would do that because you create a brand new instance of the dialog using
PageSetupDialog pageSetup = new PageSetupDialog();
What else could you expect?

You really need to re-use the same object over and over. The best and most universal way to do that on-demand using lazy initialization pattern, see[^].

I would simply keep the reference to the dialog as a field of the main form, so the whole picture would look like this:

public class MainForm : Form {
    PageSetupDialog PageSetupDialog {
        get {
            if (fPageSetupDialog == null) {
                fPageSetupDialog = new PageSetupDialog();
                fPageSetupDialog.PrinterSettings = new System.Drawing.Printing.PrinterSettings();
                fPageSetupDialog.PageSettings = new System.Drawing.Printing.PageSettings();
                fPageSetupDialog.EnableMetric = false;
            return fPageSetupDialog;
    } //PageSetupDialog

    PageSetupDialog fPageSetupDialog; //null at first, don't use it directly


    void SomeMethodWherePageSetupDialogIsUsed() {
        // of the very first call, an instance will be created
        // on other calls, same instance will be used
        // preserving all the previous settings
    } //SomeMethodWherePageSetupDialogIsUsed

} //class MainForm


This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 ppolymorphe 225
1 Afzaal Ahmad Zeeshan 165
2 OriginalGriff 150
3 George Jonsson 145
4 CPallini 100
0 OriginalGriff 3,405
1 Maciej Los 1,990
2 CPallini 1,955
3 KrunalRohit 1,907
4 ppolymorphe 1,407

Advertise | Privacy | Mobile
Web01 | 2.8.151002.1 | Last Updated 25 Dec 2011
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100