@Primer , Welcome to Microsoft Q&A, you could set a bool variable to check if the another form is opened. Then you could use datagirdview.Datasource to add the data in the second form.
Here is a code example you could refer to.
Form1:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
DataTable dataTable = new DataTable();
dataTable.Columns.Add("select",typeof(bool));
dataTable.Columns.Add("Col1",typeof(string));
dataTable.Columns.Add("Col2", typeof(string));
dataTable.Columns.Add("Col3", typeof(string));
dataTable.Columns.Add("Col4", typeof(string));
dataTable.Rows.Add(false, "test1", "test2", "test3", "test4");
dataTable.Rows.Add(false, "test3", "test4", "test5", "test6");
dataTable.Rows.Add(false, "test5", "test6", "test7", "test8");
dataTable.Rows.Add(false, "test7", "test8", "test9", "test10");
dataGridView1.AllowUserToAddRows = false;
dataGridView1.DataSource = dataTable;
}
bool t = false;
private void button1_Click(object sender, EventArgs e)
{
List<CommonValue> CV = new List<CommonValue>();
foreach (DataGridViewRow item in dataGridView1.Rows)
{
if (Convert.ToBoolean(item.Cells[0].Value))
{
CV.Add(new CommonValue
{
Colum1 = item.Cells[1].Value.ToString(),
Colum2 = item.Cells[2].Value.ToString(),
Column3 = item.Cells[3].Value.ToString()
});
}
}
if(t==false)
{
Form2 form2 = new Form2();
form2.Show();
t = true;
form2.gridView.DataSource=CV;
}
else
{
Form2 form2 = (Form2)Application.OpenForms["Form2"];
List<CommonValue> list =(List<CommonValue>)form2.gridView.DataSource;
list.AddRange(CV.ToArray());
form2.gridView.DataSource = null;
form2.gridView.DataSource = list;
}
}
}
public class CommonValue
{
public string Colum1 { get; set; }
public string Colum2 {get; set; }
public string Column3 { get; set; }
}
Form2:
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
public DataGridView gridView
{
get
{
return dataGridView1;
}
set
{
dataGridView1 = value;
}
}
}
Tested result:
Best Regards,
Jack
If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.