0
votes

I have a form with 2 datagridviews, I want to know how to properly import from "datagridview1" ONLY the selected rows into the 2nd datagridview "DatagridCopy"?

I want to create a new DataTable from the selected row(s) and make that DataTable the datasource for DatagridCopy.

I keep getting this error:

Additional information: Type of value has a mismatch with column type Couldn't store <8S3501> in t101PARTDataGridViewTextBoxColumn Column. Expected type is DataGridViewTextBoxCell.

     DataTable dt = new DataTable();
     foreach (DataGridViewColumn column in dataGridView1.Columns)
             {
             dt.Columns.Add(column.Name, column.CellType); //better to have cell type TextBoxCell.
              for (int i = 0; i < dataGridView1.SelectedRows.Count; i++)
                {
                   dt.Rows.Add();
                   for (int j = 0; j < dataGridView1.Columns.Count; j++)
                    {
                     dt.Rows[i][j] = dataGridView1.SelectedRows[i].Cells[j].Value; //ERROR HERE<-----
                    }
                }
            }
BindingSource binding = new BindingSource();
binding.DataSource = dt;
DatagridCopy.DataSource = binding;
1
I have edited your title. Please see, "Should questions include “tags” in their titles?", where the consensus is "no, they should not".John Saunders

1 Answers

2
votes

DataTable is supposed to keep data, without any visual information, but by

 dt.Columns.Add(column.Name, column.CellType); 

you are telling it that the data will DataGridViewTextBoxCell, but then here

dt.Rows[i][j] = dataGridView1.SelectedRows[i].Cells[j].Value;

you assign actual value instead of a cell. Try just dt.Columns.Add(column.Name), or dt.Columns.Add(column.Name, typeof(string)) or whatever type it actually is.

If you want your cells to be a particular type, you need to set up DatagridCopy, not dt.