E
E
Eugene2014-09-29 06:53:29
Programming
Eugene, 2014-09-29 06:53:29

Why is printing happening twice in a row?

Hello.
There are two buttons and the same event for printing a file.
But on one button (btnPrintDetails) it prints normally, and on the second (btnPrint) - two or more times (as if the button is pressed several times).
I write the following:

Button btnPrint = new Button();
private void DetailsViews(TableLayoutPanel tblDetails)
{
...
Button btnPrintDetails = new Button();
...
btnPrintDetails.Click += new EventHandler(btnPrintDetailsClick);
}

private void dropDownClosedYearMonth(object sender, EventArgs e)
{
...
btnPrint.Text = "Распечатать";
btnPrint.Click += new EventHandler(btnPrintClick);
btnPrint.Height = _buttonHeight - 30;
btnPrint.FlatStyle = FlatStyle.System;
btnPrint.Dock = DockStyle.Top;
btnPrint.Visible = true;
}

private void btnPrintDetailsClick(object sender, EventArgs e)
        {
// тут еще код для кнопки 1
........
            PrintDocument _print = new PrintDocument();

            _print.DocumentName = docname;
            _print.PrintPage += new PrintPageEventHandler(printPage);
            _print.DefaultPageSettings.Margins = new Margins(3, 3, 3, 3);
            _print.Print();
        }

void btnPrintClick(object sender, EventArgs e)
        {
// тут еще код для кнопки 2
....
                PrintDocument _print = new PrintDocument();

                _print.DocumentName = docname;
                _print.PrintPage += new PrintPageEventHandler(printPage);
                _print.DefaultPageSettings.Margins = new Margins(3, 3, 3, 3);
                _print.Print();

        }

        private void printPage(object sender, PrintPageEventArgs e)
        {
            Font font = new Font("Arial", 12);

            string stringToPrint = System.IO.File.ReadAllText(docname, Encoding.UTF8);

            int charactersOnPage = 0;
            int linesPerPage = 0;

            e.Graphics.MeasureString(stringToPrint, font, e.MarginBounds.Size, StringFormat.GenericTypographic, out charactersOnPage, out linesPerPage);
            e.Graphics.DrawString(stringToPrint, font, Brushes.Black, e.MarginBounds, StringFormat.GenericTypographic);
            stringToPrint = stringToPrint.Substring(charactersOnPage);

            e.HasMorePages = (stringToPrint.Length > 0);
        }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
aush, 2014-09-29
@gloomkolomna

private void dropDownClosedYearMonth(object sender, EventArgs e)
{
    btnPrint.Click += new EventHandler(btnPrintClick);
}

For every dropDownClosedYearMonth you add a new btnPrintClick handler. Accordingly, how many times you call dropDownClosedYearMonth, so many times it will then go to print when btnPrint is pressed. Why are you initializing btnPrint in dropDownClosedYearMonth and not in the form's constructor?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question