0

I need to copy a DGV from a bounded DGV to a normal DGV.

Reason: I need to add combobox-columns after load from Dataset and thats not possible on bound-DGV. So I tried to copy the content in new DGV. Any better ideas??

I used this to copy the dgv: copy Datagrids

Then i wrote this to test it with a button:

private void button1_Click(object sender, EventArgs e)
    {
        dgvExcel2.AutoGenerateColumns = true;
        dgvExcel2 = CopyDataGridView(dgvExcel);
        dgvExcel2.Refresh();
        dgvExcel2.Show();
        dgvExcel2.Update();
    }

(Update, Show, Refresh just to try something because it doesn' work)

When I run the program on UI the dgvExcel2 is always empty. But when i debug i see that there is content in data.

Community
  • 1
  • 1
Atzen444
  • 13
  • 2

1 Answers1

0

If I remember correctly you can't have AutoGenerateColumns set to true if you want ComboBox functionality. This needs to be predefined in your DataGridView as a DataGridViewComboBoxColumn.

Also best practices would not be to copy data to and from DGVs, but rather handle this behind UI with DataTables or List<T>.

Please see the following answers:

DataGridView set column cell Combobox

Bind Data to the Windows Forms DataGridView Control

Edit:

Handling your data in a datatable behind the UI as opposed to copying the rows directly between the DGVs seems to resolve your issue. This would remove the need for that Copy DGV method and make your life a lot easier.

The steps would :

  1. Get your data in DataTable format (myData)
  2. instantiate a BindingSource:

    BindingSource binding = new BindingSource();

  3. Assign datatable to binding source:

    binding.DataSource = myData;

  4. Then assign that binding source to your relevant DGVs.

    myDataGridView.DataSource = binding;

  5. Then instead of copying rows across your DGVs you can just reassign your bindings, or create new ones for the new DGV and assign the same datatable to the new binding.

I hope this is clearer and I have understood the question correctly.

Community
  • 1
  • 1
Mark Atkinson
  • 458
  • 8
  • 14
  • sorry, maybe I explained it to bad. My first problem is that the dgvExcel2 doesnt show the data on UI. I didnt add the ComboBox-Row yet. But good to know for the future. – Atzen444 Oct 13 '16 at 08:19
  • Ahh okay, I will add an edit, are using bindingsources? – Mark Atkinson Oct 13 '16 at 08:23
  • If I do this then are both DGVs are binded...I need 1 dgv that contains the data without binding. You cant add a combobox-Row in bounded DGVs. – Atzen444 Oct 13 '16 at 09:19
  • You sure can, check out this answer: [BindingSource with DataGridView Combo Box](http://stackoverflow.com/questions/13829621/bindingsource-with-datagridview-combo-box) – Mark Atkinson Oct 13 '16 at 09:28