I have a datagridview in form 1 which contains unbound data. How can I transfer the data from datagridview in another datagridview2 which is located in form2? Give me some suggestions please!
2 Answers
If you had the DataGridView bound to a table, you would just set a reference in Form2 to the table. In your case, you probably want to have a reference to the actual DataGridView in the second form.
It's not the best programming style from a maintenance perspective — it's better to use a data source.
Here is a simple idea of one way to show the second DataGridView with the data from the first DataGridView. It's not perfect, but it should show you the idea.
public Form2(DataGridView dgvFromFom1) {
InitializeComponent();
foreach (DataGridViewColumn dc in dgvFromForm1.Columns) {
dataGridView1.Columns.Add(dc.Name, dc.HeaderText);
}
foreach (DataGridViewRow dr in dgvFromForm1.Rows) {
Object[] newRow = new object[dr.Cells.Count];
for (int i = 0; i < newRow.Length; i++) {
newRow[i] = dr.Cells[i].Value;
}
dataGridView1.Rows.Add(newRow);
}
}
Again, though, this would be a lot easier using a DataSource.
You do not need to transfer data betwwen Forms or Grids. The thing is that if you figure our that need to share a data between them, just define a facade class that holds a data, and all that parts of your application (Forms, Grids, something else) consume data from that single, exactly same instance.
That is.