Wednesday, January 08, 2014

How to convert DataGridView DataTable / DataGrid to DataTable



How to convert DataGridView DataTable


private DataTable ToDataTableASM(DataGridView dataGridView, string tableName)
        {
            DataGridView dgv = dataGridView;
            DataTable table = new DataTable(tableName);

            // Create  columnas
            for (int iCol = 0; iCol < dgv.Columns.Count; iCol++)
            {  
                    table.Columns.Add(dgv.Columns[iCol].Name);
            }

            /* THIS WORKS  DataGrid to DataTable... */

            foreach (DataGridViewRow row in dgv.Rows)
            {
                DataRow datarw = table.NewRow();
                for (int iCol = 0; iCol < dgv.Columns.Count; iCol++)
                {
                    try
                    {
                        datarw[iCol] = row.Cells[iCol].Value;
                    }
                    catch (Exception ex)
                    { }
                }

                table.Rows.Add(datarw);
            }
            return table;
        }

No comments:

Post a Comment