将datagridview从一个表单传递到另一个表单c#

我想将我的datagridview从form1传递给form2.I尝试了构造函数但没有结果,第二种forms的datagridview为空。 有人可以在这里帮助我,我堆积了几个小时。我不使用sql,我不需要使用dataTable.Here是我的代码:

我在datagridview2的cellClick事件上填充datagridview3。 当我点击dayagridview2 cellClick_event时,我的datagridview3填充了这个方法:

private void dataGridView2_CellClick(object sender, DataGridViewCellEventArgs e) { DataD d = new DataD(); d.Mat(dataGridView1,dataGridView2,dataGridView3); } 

这是填充dataGridView3的方法:

  public void Mat(DataGridView dataGridView1, DataGridView dataGridView2,DataGridView dataGridView3) { Named n = new Named(); foreach (DataGridViewCell cell in dataGridView2.SelectedCells) { IList lista = new List(); n.Data = string.Empty; n.Data2 = string.Empty; int indexOfYourColumn = 9; int index2 = 0; var restaurantList = new List(); foreach (DataGridViewRow row in dataGridView1.Rows) { n.Data = row.Cells[indexOfYourColumn].Value.ToString(); if (cell.Value.ToString() == n.Data.ToString()) { restaurantList.Add(new Nalozi() { Data = row.Cells[indexOfYourColumn].Value.ToString(), Data2 = row.Cells[index2].Value.ToString() }); } } dataGridView3.DataSource = restaurantList; } } 

所以现在我只需要在buttnClick上以另一种forms显示这个dataGridView3。

如果要将DataGridView从一个表单传递到另一个表单,则可能必须将DataGridView.DataSourceDataGridView从一个表单传递给另一个表单。 这样的事情

 new SecondForm(dataGridView.DataSource) 

并且您的SecondForm将接受传递的DataSource并将其传递给该表单的DataGridView

 class SecondForm { public SecondForm(object dataSource) { InitializeComponents(); dataGridView.DataSource = dataSource; } } 

如果要传递DataSource副本,可以从FirstForm DataGridView的现有数据创建新的DataTable

 private DataTable GetDataTableFromDGV(DataGridView dgv) { var dt = new DataTable(); foreach (DataGridViewColumn column in dgv.Columns) { if (column.Visible) { // You could potentially name the column based on the DGV column name (beware of dupes) // or assign a type based on the data type of the data bound to this DGV column. dt.Columns.Add(); } } object[] cellValues = new object[dgv.Columns.Count]; foreach (DataGridViewRow row in dgv.Rows) { for (int i = 0; i < row.Cells.Count; i++) { cellValues[i] = row.Cells[i].Value; } dt.Rows.Add(cellValues); } return dt; } 

并更新第一次调用此

 new SecondForm(GetDataTableFromDGV(dataGridView))