none
Copy all data from Datagridview into a new datatable

    Question

  • Hi, I was wondering if any have done this before.  What I need to do is, copy all the data from a Datagridview into a datatable. 

    Please reply back if you can help.

    Thank you.

    Rick..
    Thursday, December 28, 2006 9:29 PM

Answers

  • Hi,TommyGL

    Here I write a sample code for your information. Assume that I load some data from the database to DataGridView, them add an extra column to the DataGridView, do some calculation to assign value to this column while handling the CellValueNeeded event, by the way, to mix a DataGridView with bound and unbound column, it's recommended to set the DataGridView's VirtualMode to True.

    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;

     

    namespace Samples

    {

        public partial class BtnDrag : Form

        {

            public BtnDrag()

            {

                InitializeComponent();

            }

     

            private void BtnDrag_Load(object sender, EventArgs e)

            {

                this.dataGridView1.DataSource = this.getData().Tables[0];

                DataGridViewTextBoxColumn addrCol = new DataGridViewTextBoxColumn();

                addrCol.Name = "Address";

                addrCol.HeaderText = "Address";

                this.dataGridView1.Columns.Add(addrCol);

            }

     

            private void dataGridView1_CellValueNeeded(object sender, DataGridViewCellValueEventArgs e)

            {

                if (e.ColumnIndex == 4 && e.RowIndex != this.dataGridView1.NewRowIndex)

                    e.Value = this.dataGridView1.Rows[e.RowIndex].Cells["Country"].Value.ToString() + " " +

                        this.dataGridView1.Rows[e.RowIndex].Cells["City"].Value.ToString();

            }

     

            private void button1_Click(object sender, EventArgs e)

            {

                DataTable dt = new DataTable();

                dt = (this.dataGridView1.DataSource as DataTable).Copy();

                dt.Columns.Add("Address", typeof(string));

                for (int i = 0; i < this.dataGridView1.NewRowIndex; i++)

                {

                    dt.Rows[ i ]["Address"] = this.dataGridView1.Rows[ i ].Cells["Address"].Value;

                }

     

                this.dataGridView2.DataSource = dt;

            }

     

            public DataSet getData()

            {

                string connstr = "Persist Security Info=False;Integrated Security=SSPI;Initial Catalog=Northwind;server=localhost";

                SqlConnection conn = new SqlConnection(connstr);

                string sql = "Select CustomerId,CompanyName, Country, City from Customers";

                SqlDataAdapter Adapter = new SqlDataAdapter(sql, conn);

                DataSet ds = new DataSet();

                Adapter.Fill(ds, "Customers");

                return ds;

            }

        }

    }

    Hope it helps, Best Regards

    Ye

    Friday, January 26, 2007 6:01 AM
  • Use the for clause to loop all the rows..
    Monday, January 08, 2007 5:29 AM

All replies

  • Well, you can't copy it "from a DataGridView", but you can copy it from it's DataSource.  The DataSource can be an type of Object which implements either IList or IListSource. 

    Now, if that object happens to be a DataTable then it shouldn't be that hard:


    public DataTable ExtractDataTable(DataGridView dgv)
    {
          DataTable dtSrc = dgv.DataSource as DataTable;
          DataTable dtDest = null;
          if (dtSrc != null)
          {
               DataTable dtDest = new DataTable();
               dtDest.Merge(dtSrc);
          }
          return dtDest;
    }

     

    If the DataSource is any other type of object, then it become much trickier, and is much easier to return it as an ArrayList:


    public ArrayList ExtractDataSource(DataGridView dgv)
    {
          Object ds = dgv.DataSource;
          IList il  = null;
          if (ds is IListSource)
               il = (ds as IListSource).GetList();
         else
               il = (ds as IList);
         return new ArrayList(il)
        }

     
            
         

    Thursday, December 28, 2006 9:56 PM
  • Thanks for the quick reply there.  I forgot to mention that the Datagridview have some unbounded columns in addition to the data bounded columns.  I want the data from the unbounded columns copied too.   Will the example (copy DataGridView to datatable) sill work?

    Thanks again.

    Rick..
    Thursday, December 28, 2006 10:19 PM
  • Use the for clause to loop all the rows..
    Monday, January 08, 2007 5:29 AM
  • Hi, what I did was in the end was, loop thru each row in the grid as I save them in a table in my dataset.

    Thanks for the help.

    Rick..
    Monday, January 15, 2007 3:03 AM
  • hi rick, do you mind to share the coding on how you loop thru the rows and save into dataset? thank you for your help.
    Friday, January 26, 2007 3:38 AM
  • Hi,TommyGL

    Here I write a sample code for your information. Assume that I load some data from the database to DataGridView, them add an extra column to the DataGridView, do some calculation to assign value to this column while handling the CellValueNeeded event, by the way, to mix a DataGridView with bound and unbound column, it's recommended to set the DataGridView's VirtualMode to True.

    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;

     

    namespace Samples

    {

        public partial class BtnDrag : Form

        {

            public BtnDrag()

            {

                InitializeComponent();

            }

     

            private void BtnDrag_Load(object sender, EventArgs e)

            {

                this.dataGridView1.DataSource = this.getData().Tables[0];

                DataGridViewTextBoxColumn addrCol = new DataGridViewTextBoxColumn();

                addrCol.Name = "Address";

                addrCol.HeaderText = "Address";

                this.dataGridView1.Columns.Add(addrCol);

            }

     

            private void dataGridView1_CellValueNeeded(object sender, DataGridViewCellValueEventArgs e)

            {

                if (e.ColumnIndex == 4 && e.RowIndex != this.dataGridView1.NewRowIndex)

                    e.Value = this.dataGridView1.Rows[e.RowIndex].Cells["Country"].Value.ToString() + " " +

                        this.dataGridView1.Rows[e.RowIndex].Cells["City"].Value.ToString();

            }

     

            private void button1_Click(object sender, EventArgs e)

            {

                DataTable dt = new DataTable();

                dt = (this.dataGridView1.DataSource as DataTable).Copy();

                dt.Columns.Add("Address", typeof(string));

                for (int i = 0; i < this.dataGridView1.NewRowIndex; i++)

                {

                    dt.Rows[ i ]["Address"] = this.dataGridView1.Rows[ i ].Cells["Address"].Value;

                }

     

                this.dataGridView2.DataSource = dt;

            }

     

            public DataSet getData()

            {

                string connstr = "Persist Security Info=False;Integrated Security=SSPI;Initial Catalog=Northwind;server=localhost";

                SqlConnection conn = new SqlConnection(connstr);

                string sql = "Select CustomerId,CompanyName, Country, City from Customers";

                SqlDataAdapter Adapter = new SqlDataAdapter(sql, conn);

                DataSet ds = new DataSet();

                Adapter.Fill(ds, "Customers");

                return ds;

            }

        }

    }

    Hope it helps, Best Regards

    Ye

    Friday, January 26, 2007 6:01 AM
  • Thank you very much for the help. Really appreciate it.
    Friday, January 26, 2007 7:10 AM