Click here to Skip to main content
12,897,431 members (51,750 online)
Rate this:
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.

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
Top Experts
Last 24hrsThis month

Advertise | Privacy | Mobile
Web02 | 2.8.170424.1 | Last Updated 25 Dec 2011
Copyright © CodeProject, 1999-2017
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