Preventing hidden fields from being transferred to Word

mfatih

New member
Joined
Dec 4, 2023
Messages
4
Programming Experience
Beginner
I want to transfer the columns I imported into Datagridview to Word with Checkbox. However, it is marked with checkboxes and its hidden columns, which are not visible in the datagridview, are also transferred to Word. I would like to convey only their tentative summaries, which will be included in the picture. What's the solution?
1.png
 
Last edited by a moderator:
C#:
using System;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using Word = Microsoft.Office.Interop.Word;

namespace SinifListesi
{
    public partial class WordeAktar : Form
    {
        public WordeAktar()
        {
            InitializeComponent();
        }
        OleDbConnection conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source = siniflisteleri25.accdb; Jet OLEDB:Database Password = Fatih2541; Mode = ReadWrite");
        OleDbCommand sorgu;
        OleDbDataReader veriler;


        private void SinifCek()
        {
            try
            {
                if (conn.State == ConnectionState.Closed)
                {
                    conn.Open();
                }
                sorgu = new OleDbCommand
                {
                    CommandText = "SELECT * from siniflar order by sin_id asc",
                    Connection = conn
                };
                veriler = sorgu.ExecuteReader();
                while (veriler.Read())
                {

                    ComboBox1.Items.Add(veriler["sinifi"].ToString());
                    ComboBox1.ValueMember = "sinifi";
                    ComboBox1.DisplayMember = "sinifi";
                }
                veriler.Close();
                sorgu.Dispose();
            }
            catch (Exception hata)
            {
                MessageBox.Show("Islem Sirasinda Hata Olustu." + hata.Message);
            }
        }

        public void Export_Data_To_Word(DataGridView DGV, string filename)
        {
            if (File.Exists(filename))
            {
                File.Delete(filename);
            }
            Word.Document oDoc = new Word.Document();
            oDoc.Application.Visible = true;


            if (DGV.Rows.Count != 0)
            {
                int RowCount = DGV.Rows.Count;
                int ColumnCount = DGV.Columns.Count;
                Object[,] DataArray = new object[RowCount + 1, ColumnCount + 1];

                //add rows
                int r = 0;
                for (int c = 0; c <= ColumnCount - 1; c++)
                {
                    if (DGV.Columns[c].Visible) // Check if the column is visible
                    {
                        for (r = 0; r <= RowCount - 1; r++)
                        {
                            DataArray[r, c] = DGV.Rows[r].Cells[c].Value;
                        } //end row loop

                    } //end column loop
                }


                //page orintation
                oDoc.PageSetup.Orientation = Word.WdOrientation.wdOrientLandscape;
                dynamic oRange = oDoc.Content.Application.Selection.Range;
                string oTemp = "";
                for (r = 0; r <= RowCount - 1; r++)
                {
                    for (int c = 0; c <= ColumnCount - 1; c++)
                    {
                        oTemp = oTemp + DataArray[r, c] + "\t";
                    }
                }

                //table format
                oRange.Text = oTemp;

                object Separator = Word.WdTableFieldSeparator.wdSeparateByTabs;
                object ApplyBorders = true;
                object AutoFit = true;
                object AutoFitBehavior = Word.WdAutoFitBehavior.wdAutoFitContent;

                oRange.ConvertToTable(ref Separator, ref RowCount,
                                           ref ColumnCount,
                                      Type.Missing, Type.Missing,
                                           ref ApplyBorders,
                                      Type.Missing, Type.Missing, Type.Missing,
                                      Type.Missing, Type.Missing, Type.Missing,
                                      Type.Missing, ref AutoFit,
                                           ref AutoFitBehavior, Type.Missing);
                oRange.Select();
                oDoc.Application.Selection.Borders.InsideLineStyle = Word.WdLineStyle.wdLineStyleSingle; //tablo çizgisi
                oDoc.Application.Selection.Borders.OutsideLineStyle = Word.WdLineStyle.wdLineStyleSingle; // tablo çizgisi
                oDoc.Application.Selection.Tables[1].Select();
                oDoc.Application.Selection.Tables[1].Rows.AllowBreakAcrossPages = 0;
                oDoc.Application.Selection.Tables[1].Rows.Alignment = 0;
                oDoc.Application.Selection.Tables[1].Rows[1].Select();
                oDoc.Application.Selection.InsertRowsAbove(1);
                oDoc.Application.Selection.Tables[1].Rows[1].Select();

                //header row style
                oDoc.Application.Selection.Tables[1].Rows[1].Range.Bold = 1;
                oDoc.Application.Selection.Tables[1].Rows[1].Range.Font.Name ="Tahoma";
                oDoc.Application.Selection.Tables[1].Rows[1].Range.Font.Size = 14;

                //add header row manually
                for (int c = 0; c <= DGV.Columns.Count - 1; c++)
                {
                    if (DGV.Columns[c].Visible) // Check if the column is visible
                    {
                        oDoc.Application.Selection.Tables[1].Cell(1, c + 1).Range.Text = DGV.Columns[c].HeaderText;
                    }
                }

                //table style
                oDoc.Application.Selection.Tables[1].Rows[1].Select();
                oDoc.Application.Selection.Cells.VerticalAlignment =
                    Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;

                //header text
                foreach (Word.Section section in
                         oDoc.Application.ActiveDocument.Sections)
                {
                    Word.Range headerRange =section.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
                    headerRange.Fields.Add(headerRange,
                       Word.WdFieldType.wdFieldPage);
                    headerRange.Text = "ÖGRENCI BILGILERI";
                    headerRange.Font.Size = 16;
                    headerRange.ParagraphFormat.Alignment =
                       Word.WdParagraphAlignment.wdAlignParagraphCenter;
                }

                //save the file
                oDoc.SaveAs2(filename);
                MessageBox.Show("Ögrenci bilgileri word dosyasina aktarildi.");
                oDoc.Close();
                oDoc.Application.Quit();
            }
        }

        private void WordeAktar_Load(object sender, EventArgs e)
        {
            SinifCek();
            ComboBox1.SelectedIndex = 0;

            DGV.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
            DGV.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;

            DGV.Columns["tcno"].Visible = tcnochk.Checked; // ilk açilista hangi sütunlari getirecegiyle ilgili
            DGV.Columns["dtarihi"].Visible = dogchk.Checked;
            DGV.Columns["atel"].Visible = atelchk.Checked;
            DGV.Columns["btel"].Visible = btelchk.Checked;


            DGV.TopLeftHeaderCell.Value = "S.No";
            DGV.Columns[0].HeaderText = "T.C.No";
            DGV.Columns[1].HeaderText = "Ö.No";
            DGV.Columns[2].HeaderText = "Adi";
            DGV.Columns[3].HeaderText = "Soyadi";
            DGV.Columns[4].HeaderText = "Cinsiyeti";
            DGV.Columns[5].HeaderText = "Sinifi";
            DGV.Columns[7].HeaderText = "Anne Tel";
            DGV.Columns[8].HeaderText = "Baba Tel";
        }

        private void button1_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();

            sfd.Filter = "Word Documents (*.docx)|*.docx";

            sfd.FileName = "Ögrenci Bilgileri.docx";

            if (sfd.ShowDialog() == DialogResult.OK)
            {

                Export_Data_To_Word(DGV, sfd.FileName);
            }
        }

        private void ComboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            using (OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source = siniflisteleri25.accdb; Jet OLEDB:Database Password = Fatih2541; Mode = ReadWrite"))
            {

                string query = "SELECT tcno,ono,isim,soyisim,cinsiyet,sinifi,dtarihi,atel,btel from ogrencibilgileri25 where sinifi='" + ComboBox1.Text + " '";

                OleDbCommand command = new OleDbCommand(query, conn);
                conn.Open();
                var adapter = new OleDbDataAdapter(command);
                var table = new DataTable();
                adapter.Fill(table);
                DGV.DataSource = table;
                conn.Close();
            }
        }

        private void tcnochk_CheckedChanged(object sender, EventArgs e)
        {
            DGV.Columns["tcno"].Visible = tcnochk.Checked;
        }

        private void dogchk_CheckedChanged(object sender, EventArgs e)
        {
            DGV.Columns["dtarihi"].Visible = dogchk.Checked;
        }

        private void atelchk_CheckedChanged(object sender, EventArgs e)
        {
            DGV.Columns["atel"].Visible = atelchk.Checked;
        }

        private void btelchk_CheckedChanged(object sender, EventArgs e)
        {
            DGV.Columns["btel"].Visible = btelchk.Checked;
        }

        private void DGV_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            var grid = sender as DataGridView;
            var rowIdx = (e.RowIndex + 1).ToString();

            var centerFormat = new StringFormat()
            {
                // right alignment might actually make more sense for numbers
                Alignment = StringAlignment.Center,
                LineAlignment = StringAlignment.Center
            };

            var headerBounds = new Rectangle(e.RowBounds.Left, e.RowBounds.Top, grid.RowHeadersWidth, e.RowBounds.Height);
            e.Graphics.DrawString(rowIdx, this.Font, SystemBrushes.ControlText, headerBounds, centerFormat);
        }
    }
}
 
Unfortunately, this is a an English language forum, can you post a translation of your question from your original post?
 
Anyway, part of your problem lies in the fact that you are using your DataArray to build up your table in word, but the way you are constructing your DataArray does not account for the invisible columns. Yes, your line 72 skips the invisible column, but all you are doing is leaving an empty column in your [iocde]DataArray[/icode] by also skipping the corresponding column.

Assuming you want to minimize changing your current code, one thing that could be done is to collect references to your visible columns into a list. Then have your existing code iterate over that list of columns, rather than the actual data grid view columns. Accordingly, you should allocate your DataArray to have just the number of data columns.

But if you are willing to change your code more, why do you even need that DataArray? Why not just build up that oTemp directly instead of using that intermediate array?

But the real source of your problem is that you are using your UI as your data model. You shouldn't be using your UI to store your data. The UI is only meant to give the user a view into your data. If you kept your data in a list, then you wouldn't even have to figure out which columns are visible or not. You would know right away which parts of your data you want to put into Word, regardless of the UI.
 
Anyway, part of your problem lies in the fact that you are using your DataArray to build up your table in word, but the way you are constructing your DataArray does not account for the invisible columns. Yes, your line 72 skips the invisible column, but all you are doing is leaving an empty column in your [iocde]DataArray[/icode] by also skipping the corresponding column.

Assuming you want to minimize changing your current code, one thing that could be done is to collect references to your visible columns into a list. Then have your existing code iterate over that list of columns, rather than the actual data grid view columns. Accordingly, you should allocate your DataArray to have just the number of data columns.

But if you are willing to change your code more, why do you even need that DataArray? Why not just build up that oTemp directly instead of using that intermediate array?

But the real source of your problem is that you are using your UI as your data model. You shouldn't be using your UI to store your data. The UI is only meant to give the user a view into your data. If you kept your data in a list, then you wouldn't even have to figure out which columns are visible or not. You would know right away which parts of your data you want to put into Word, regardless of the UI.
Thanks for your interest. I am new in C#. I don't have an idea about correcting the codes. Would you mind modifying the codes for me, plaese?
 
Sorry, this site is not a code writing service. It's meant to help you learn how to program, not to spoonfeed you.
 

Latest posts

Back
Top Bottom