In this example, We’ll learn how to copy selected rows of one datagridview to another datagridview on Button Click.
Step 1: Form1 Design
Step 2: Go to the properties window by clicking on the dataGridView1 control. Change the SelectionMode to FullRowSelect property of the dataGridView control.
Step 3: Add the following code to Form_Load event.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
private void Form1_Load(object sender, EventArgs e) { //datagridview1 Columns dataGridView1.ColumnCount = 4; dataGridView1.Columns[0].Name = "Book"; dataGridView1.Columns[1].Name = "Borrowed Date"; dataGridView1.Columns[2].Name = "Delivered Date"; //datagridview2 Columns dataGridView2.ColumnCount = 4; dataGridView2.Columns[0].Name = "Book"; dataGridView2.Columns[1].Name = "Borrowed Date"; dataGridView2.Columns[2].Name = "Delivered Date"; dataGridView1.Rows.Add("Book 1", "13.01.2018", "20.01.2018"); dataGridView1.Rows.Add("Book 2", "05.03.2018", "13.03.2018"); dataGridView1.Rows.Add("Book 3", "20.04.2018", "15.05.2018"); dataGridView1.Rows.Add("Book 4", "18.04.2018", "11.05.2018"); dataGridView1.Rows.Add("Book 5", "01.06.2018", "22.08.2018"); dataGridView1.Rows.Add("Book 6", "30.05.2018", "02.06.2018"); dataGridView1.Rows.Add("Book 7", "04.04.2018", "12.05.2018"); dataGridView1.Rows.Add("Book 8", "12.03.2018", "10.04.2018"); } |
Step 4 : Add the following code to Button1_Click.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
private void button1_Click(object sender, EventArgs e) { foreach (DataGridViewRow row in dataGridView1.SelectedRows) { object[] rowData = new object[row.Cells.Count]; for (int i = 0; i < rowData.Length; ++i) { rowData[i] = row.Cells[i].Value; } this.dataGridView2.Rows.Add(rowData); } } |
Finally: