Click here to Skip to main content
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 17: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 OriginalGriff 6,055
1 DamithSL 4,621
2 Maciej Los 4,087
3 Kornfeld Eliyahu Peter 3,500
4 Sergey Alexandrovich Kryukov 3,294

Advertise | Privacy | Mobile
Web03 | 2.8.141220.1 | Last Updated 25 Dec 2011
Copyright © CodeProject, 1999-2014
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