none
How to print selected checkbox in datagridview and in case no checked print all RRS feed

  • Question

  • Actually I need to print records have checkbox checked = true inside datagridview

    And if no any record checkbox checked meaning = false checked print all

    I need to do that under button print .

    No need to go inside code details I need only to implement only pseudo code below :

    pseudo code

    if(any records checked checkbox = true)
    
        print checked only in datagridview
    
    else
    
        print all in datagridview(in case no any checkbox checked inside grid)

    my current code print all :

    private void btnPrint_Click(object sender, EventArgs e)
    {
        for (int i = 0; i < Grid.Rows.Count; i++)
        {
            if (string.IsNullOrEmpty(Convert.ToString(Grid.Rows[i].Cells["ItemCode"].Value))) return;
            Dictionary<string, string> Formulas = new Dictionary<string, string>();
            Formulas.Add("ImgFlds", BarcodePath);
            for (int x = 0; x < 4; x++)
            {
                string formula = "";
                int fieldVal = 0;
    
                if (x == 0)
                {
                    formula = "lefttopcap";
                    fieldVal = lefttopcap;
                }
                else if (x == 1)
                {
                    formula = "righttopcap";
                    fieldVal = righttopcap;
                }
                else if (x == 2)
                {
                    formula = "leftbottomcap";
                    fieldVal = leftbottomcap;
                }
                else if (x == 3)
                {
                    formula = "rightbottomcap";
                    fieldVal = rightbottomcap;
                }
    
                switch (fieldVal)
                {
                    case 1:
                        break;
                    case 2:
                        Formulas.Add(formula, Convert.ToString(Grid.Rows[i].Cells["CompanyName"].Value));
                        break;
                    case 3:
                        Formulas.Add(formula, Convert.ToString(Grid.Rows[i].Cells["BranchName"].Value));
                        break;
                    case 4:
                        Formulas.Add(formula, Convert.ToString(Grid.Rows[i].Cells["ItemLatName"].Value));
                        break;
                    case 5:
                        Formulas.Add(formula, Convert.ToString(Grid.Rows[i].Cells["ItemAraName"].Value));
                        break;
                    case 6:
                        Formulas.Add(formula, Convert.ToString(Grid.Rows[i].Cells["SelPrice1"].Value));
                        break;
    
                    default:
                        break;
                }
            }
    
            string sql = "select * from Branches where 1=1 ";
            int z = !string.IsNullOrEmpty(Convert.ToString(Grid.Rows[i].Cells["ItemCount"].Value)) ? Convert.ToInt32(Convert.ToString(Grid.Rows[i].Cells["ItemCount"].Value)) : 1;
    
            Reporting.PrinterName = cmbPrinterType.Text; 
            Reporting.PrintType = PrintTypes.Print;
            CreateBarcode(Convert.ToString(Grid.Rows[i].Cells["code"].Value).Trim());
            picItem.Image.Save(BarcodePath);
            Reporting.ShowReport("BarcodePrinting.rpt", sql, Formulas, z);
        }
    }


    to get checked checkbox in data gridview as following

    bool isSelected = Convert.ToBoolean(Grid.Rows[i].Cells["SelectedPrint"].Value);
    if (isSelected)
    {
    }


    Sunday, March 11, 2018 8:26 PM

All replies

  • Hello,

     Just loop through each object and if check = true then print object.

    What is the purpose of print all objects that are check false? You could

    code the Checked event handler to save that object to container, i.e.

    List<>, or Stack<>, etc.  If the the container count != zero then print

    those object as a reference to Grid.Row objects.  I guess you want to

    Print Selected and Print All in the same button event? There are many

    methods of code to implement your request. Most depend on the app

    flow and your preference.

     

     BTW, the code your provide could use some improvements. Perhaps

    the IF/ELSE and SWITCH code could be merged into SWITCH/CASE.

    The basic structure of SWITCH/CASE is a series of IF/GOTO statements.

     Hope this helps :)


    Sunday, March 11, 2018 10:42 PM
  • thank you for reply 

    can you tell me how to do that 

    or give me sample for that if possible

    already i can print all records in datagridview

    i need only to print checked checkbox on datagridview

    Sunday, March 11, 2018 11:11 PM
  • Hello,

     Perhaps the following code will work for you, adjust variable names

    to match your code;

    for ( int x=0; x < this.dataGridView1.NewRowIndex; x++)
    {
        DataGridViewRow dgvRow = this.dataGridView1.Rows[ x ];
    
        // my code, "Selection" is the
        // 1st Column formatting style
        // DataGridViewCheckBoxColumn
        //
        if ( dgvRow.Cells[ "Selection" ].Value.Equals( true ) )
        {
            // call your print code
            // use variable 'x' value
            // as the RowIndex
            // See my example
            SimulatePrint( x );
        }
    }
    
    private void SimulatePrint( int x )
    {
        // create temp variable for readability
        //
        DataGridViewRow dgvRow = this.dataGridView1.Rows[ x ];
    
        this.textBox1.Text += string.Format( "MAKE:  {0}\r\n", dgvRow.Cells[ "Make" ].Value.ToString() );
        this.textBox1.Text += string.Format( "MODEL: {0}\r\n", dgvRow.Cells[ "Model" ].Value.ToString() );
        this.textBox1.Text += string.Format( "COLOR: {0}\r\n", dgvRow.Cells[ "Color" ].Value.ToString() );
        this.textBox1.Text += string.Format( "YEAR:  {0}\r\n", dgvRow.Cells[ "Year" ].Value.ToString() );
    
        this.textBox1.Text += string.Format( "\r\n" );
    }

    Here is the output of my project;

    What you see is the results from Selected Print. I used a TextBox container

    to simulate Printing.  You will adjust your project for your Printer code.

     

     BTW, in DataGridView the Property Selected refers to the UI highlighted not

    the checkbox state.  Because you can select or highlight any single Cell by

    column/row when Multi Select is True.

     Hope this helps :)


    • Edited by User3DX Monday, March 12, 2018 8:07 AM Addendom
    • Proposed as answer by ID GO Monday, March 12, 2018 10:14 AM
    Monday, March 12, 2018 8:01 AM
  • Hello,

    The following works against a unbound DataGridViewCheckBox column and gets cell data dependent on checked or un checked cell.

    Add The following class to your project.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Windows.Forms;
    
    static class DataGridViewExtensionMethods
    {
        /// <summary>
        /// Get checked rows by passing in the DataGridViewColumn name
        /// Get all rows by passing DataGridView column name and false for pProcess parameter
        /// </summary>
        /// <param name="pDataGridView"></param>
        /// <param name="pColumnName"></param>
        /// <param name="pProcess"></param>
        /// <returns></returns>
        public static List<DataGridViewRow> GetChecked(this DataGridView pDataGridView, string pColumnName, bool pProcess = true)
        {
            return (from rows in pDataGridView.Rows.Cast<DataGridViewRow>()
                    where Convert.ToBoolean(rows.Cells[pColumnName].Value) == pProcess select rows).ToList();
        }
        public static string Formater(this DataGridViewRow pRow, string pSeparator, string pCheckColumnName)
        {
    
            string[] values = new string[pRow.Cells.Count];
    
            for (int i = 0; i < pRow.Cells.Count; i++)
            {
                if (pRow.Cells[i].OwningColumn.Name != pCheckColumnName)
                {
                    values[i] = pRow.Cells[i].Value + "";
                }
                else
                {
                    values[i] = pCheckColumnName;
                }
    
            }
    
            return string.Join(pSeparator, values).Replace(pCheckColumnName + pSeparator, "");
        }
    }

    Add a button and this code to your form. In the following code replace "Process" with the name of the CheckBox column in your DataGridView

    private void btnPrintDataGridView_Click(object sender, EventArgs e)
    {
        var sb = new System.Text.StringBuilder();
        List<DataGridViewRow> rows = dataGridView1.GetChecked("Process");
    
        if (rows.Count == 0)
        {
            rows = dataGridView1.GetChecked("Process",false);
            foreach (DataGridViewRow row in rows)
            {
                sb.AppendLine(row.Formater("\t", "Process"));
            }
        }
        else
        {
            foreach (DataGridViewRow row in rows)
            {
                sb.AppendLine(row.Formater("\t", "Process"));
            }
        }
    
        PrintDocument p = new PrintDocument();
        p.PrintPage += delegate (object sender1, PrintPageEventArgs e1)
        {
            e1.Graphics.DrawString(sb.ToString(),
                new Font("Times New Roman",
                    12),
                new SolidBrush(Color.Black),
                new RectangleF(0,
                    0,
                    p.DefaultPageSettings.PrintableArea.Width,
                    p.DefaultPageSettings.PrintableArea.Height));
        };
        try
        {
            p.Print();
        }
        catch (Exception ex)
        {
            throw new Exception("Exception Occured While Printing", ex);
        }
    }


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites


    Monday, March 12, 2018 10:37 AM
    Moderator