Click here to Skip to main content
15,886,199 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
When I check the checkboxes in gridview and export it to CSV file for the selected records,in the CSV file 'TRUE' comes in the checkbox column. I want to remove this from the generated CSV file and display only the data,not the checkbox column. Kindly help me solve the issue


C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;
using System;




namespace KM_Artefact
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            DataGridViewCheckBoxColumn checkBoxColumn = new DataGridViewCheckBoxColumn();

            checkBoxColumn.HeaderText = "";

            checkBoxColumn.Width = 60;

            checkBoxColumn.Name = "checkBoxColumn";
            dataGridView1.Columns.Insert(0, checkBoxColumn);

        }


        private void button1_Click(object sender, EventArgs e)
        {
            try
            {

                String str = "Server=" + IPfield.Text + ";" + "database=" + DBfield.Text + ";" + "UID=" + IDfield.Text + ";" + "password=" + pwdfield.Text;
                /*String tbl = "Table=" + textBox6.Text;*/
                //System.Console.WriteLine(str);
                Boolean flag = false;


                if (DBfield.Text == "")
                {
                    MessageBox.Show("Enter database name");
                    flag = true;
                }
                else if (Queryfield.Text == "")
                {
                    MessageBox.Show("Enter SQL Query");
                    flag = true;
                }
                else if (IPfield.Text == "")
                {
                    MessageBox.Show("Enter SQL IP");
                    flag = true;
                }
                else if (IDfield.Text == "")
                {
                    MessageBox.Show("Enter Username");
                    flag = true;
                }
                else if (pwdfield.Text == "")
                {
                    MessageBox.Show("Enter Password");
                    flag = true;
                }


                if (flag == false)
                {

                    SqlConnection con = new SqlConnection(str);

                    String query = Queryfield.Text;
                    SqlCommand cmd = new SqlCommand(query, con);
                    SqlDataAdapter dataadapter = new SqlDataAdapter(query, con);
                    DataSet ds = new DataSet();
                    con.Open();
                    /*dataadapter.Fill(ds, "VMS");*/
                    dataadapter.Fill(ds, query);

                    //MessageBox.Show("connect with SQL server");
                    //MessageBox.Show("Connected");

                    DataTable dt = ds.Tables[query];


                    SaveFileDialog saveFileDialog1 = new SaveFileDialog();
                    saveFileDialog1.Filter = "CSV|*.csv";
                    saveFileDialog1.Title = "Save a CSV File";
                    //saveFileDialog1.ShowDialog();
                    DialogResult dr = saveFileDialog1.ShowDialog();

                    if (dr == DialogResult.OK)
                    {
                        string strFilePath = saveFileDialog1.FileName;
                        //save file using stream.
                        //StreamWriter sw = new StreamWriter(strFilePath, true);
                        CreateCSVFile(dt, strFilePath);
                    }

                    //CreateCSVFile(dt, "");


                    //MessageBox.Show("CSV generated");


                    con.Close();
                   // DataGridViewCheckBoxColumn checkBoxColumn = new DataGridViewCheckBoxColumn();

                   // checkBoxColumn.HeaderText = "SELECT";

                   // checkBoxColumn.Width = 60;

                    //checkBoxColumn.Name = "checkBoxColumn";
                    //dataGridView1.Columns["checkBoxColumn"].ReadOnly = false;
                    //checkBoxColumn.Selected = true;
                    //dataGridView1.Columns.Insert(0, checkBoxColumn);
                    dataGridView1.DataSource = ds;
                    dataGridView1.DataMember = query;




                }
            }

            catch (Exception es)
            {

                MessageBox.Show(es.Message);
                //MessageBox.Show("Unable to Connect \nPlease Enter Correct Credentials");




            }

        }
        public void CreateCSVFile(DataTable dt, string strFilePath)
        {

            #region Export Grid to CSV

            // Create the CSV file to which grid data will be exported.
            StreamWriter sw = new StreamWriter(strFilePath, false);
            // First we will write the headers.
            //DataTable dt = m_dsProducts.Tables[0];
            int iColCount = dt.Columns.Count;
            for (int i = 0; i < iColCount; i++)
            {
                sw.Write(dt.Columns[i]);
                if (i < iColCount - 1)
                {
                    sw.Write(",");
                }
            }
            sw.Write(sw.NewLine);
            // Now write all the rows.
            foreach (DataRow dr in dt.Rows)
            {
                for (int i = 0; i < iColCount; i++)
                {
                    if (!Convert.IsDBNull(dr[i]))
                    {
                        sw.Write(dr[i].ToString());
                    }
                    if (i < iColCount - 1)
                    {
                        sw.Write(",");
                    }
                }
                sw.Write(sw.NewLine);
            }
            sw.Close();

            #endregion
        }
       
        private void button2_Click(object sender, EventArgs e)
        {
            try
            {

                String str = "Server=" + IPfield.Text + ";" + "database=" + DBfield.Text + ";" + "UID=" + IDfield.Text + ";" + "password=" + pwdfield.Text;
                /*String tbl = "Table=" + textBox6.Text;*/
                //System.Console.WriteLine(str);
                Boolean flag = false;


                if (DBfield.Text == "")
                {
                    MessageBox.Show("Enter database name");
                    flag = true;
                }
                else if (Queryfield.Text == "")
                {
                    MessageBox.Show("Enter SQL Query");
                    flag = true;
                }
                else if (IPfield.Text == "")
                {
                    MessageBox.Show("Enter SQL IP");
                    flag = true;
                }
                else if (IDfield.Text == "")
                {
                    MessageBox.Show("Enter Username");
                    flag = true;
                }
                else if (pwdfield.Text == "")
                {
                    MessageBox.Show("Enter Password");
                    flag = true;
                }


                if (flag == false)
                {

                    SqlConnection con = new SqlConnection(str);

                    String query = Queryfield.Text;
                    SqlCommand cmd = new SqlCommand(query, con);
                    SqlDataAdapter dataadapter = new SqlDataAdapter(query, con);
                    DataSet ds = new DataSet();
                    con.Open();
                    /*dataadapter.Fill(ds, "VMS");*/
                    dataadapter.Fill(ds, query);

                    MessageBox.Show("connect with SQL server");
                    //MessageBox.Show("Connected");

                    DataTable dt = ds.Tables[query];
                    con.Close();
                   /* DataGridViewCheckBoxColumn checkBoxColumn = new DataGridViewCheckBoxColumn();

                    checkBoxColumn.HeaderText = "SELECT";

                    checkBoxColumn.Width = 60;

                    checkBoxColumn.Name = "checkBoxColumn";
                    dataGridView1.Columns.Insert(0, checkBoxColumn);*/
                   // dataGridView1.Columns["checkBoxColumn"].ReadOnly = false;
                    //checkBoxColumn.Selected = true;
                    dataGridView1.DataSource = ds;
                    dataGridView1.DataMember = query;
                    


                }
            }
                 catch (Exception es)
            {

                MessageBox.Show(es.Message);
                //MessageBox.Show("Unable to Connect \nPlease Enter Correct Credentials");




            }
 
                       
        }

        private void GetCellData(string path)
        {
            string data = "";
            //string userDesktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            TextWriter tw = new StreamWriter(path,false);

            // Count each row in the datagrid
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                
                if (dataGridView1.Rows[i].Cells["checkBoxColumn"].Value != null &&
                    (bool)dataGridView1.Rows[i].Cells["checkBoxColumn"].Value)
              
                {
                    
                    foreach (DataGridViewCell cell in dataGridView1.Rows[i].Cells)
                    for(int j=0; j < dataGridView1.Columns.Count; j++ )
                    {
                        

                       
                            data = data + (cell.Value + ",");
                     
                    }
                    data = data + "\n";
                }
                else
                {
                    continue;
                }

            }
            tw.WriteLine(data, "data");
            tw.Close();
        }

        private void button3_Click(object sender, EventArgs e)
        {


            //for (int i = 0; i < dataGridView1.Rows.Count;i++ )
           
                int i=0;
                if (dataGridView1.Rows[i].Cells["checkBoxColumn"].Value != null &&
                    (bool)dataGridView1.Rows[i].Cells["checkBoxColumn"].Value)
                {
                    //dataGridView1.Columns[0].Visible = false;
                    SaveFileDialog saveFileDialog1 = new SaveFileDialog();
                    saveFileDialog1.Filter = "CSV|*.csv";
                    saveFileDialog1.Title = "Save a CSV File";
                    //saveFileDialog1.ShowDialog();
                    DialogResult dr = saveFileDialog1.ShowDialog();

                    if (dr == DialogResult.OK)
                    {
                        string Path = saveFileDialog1.FileName;
                        //save file using stream.
                        //StreamWriter sw = new StreamWriter(strFilePath, true);
                        GetCellData(Path);
                    }
                }

                else
                {
                    //continue;
                    MessageBox.Show("Select data");

                }
            
            
            }
           
        }
        
           
                  

        }
Posted
Updated 18-Mar-15 1:30am
v2

1 solution

In the constructor of Form1 you insert checkBoxColumn at index 0. So the solution is simple: In your for-loops where you write the headers and then the rows start at index 1 instead of 0.
 
Share this answer
 
Comments
ZurdoDev 18-Mar-15 8:20am    
Exactly. +5
Member 11518617 18-Mar-15 8:25am    
it did not solve the issue
[no name] 18-Mar-15 8:30am    
Wait. Which method do you actually use here to generate the CSV? I see two in your code which do something like that.
Member 11518617 18-Mar-15 8:39am    
one method directly generates CSV(CreateCSVFile) on a button click and the other method(GetCellData) generates CSV for the selected data from gridview. My issue is when the second method generates csv,checkboxcolumn is also exported in the csv file and the checked boxes shows 'TRUE' written in the CSV file
[no name] 18-Mar-15 8:42am    
And you tried this?

for(int j=1; j < dataGridView1.Columns.Count; j++)
...............^

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900