In this example, I’ll show you how to Copy selected row from dataGridView1 to dataGridView2 in C# Windows Form Application.
Form Design:
Go to the properties window by clicking on the dataGridView1 control.
Change the SelectionMode to FullRowSelect property of the dataGridView control.
Add the following code to Form_Load event and Button1_Click.
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 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace datagrid_1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { //datagridview1 Columns dataGridView1.ColumnCount = 3; dataGridView1.Columns[0].Name = "ID"; dataGridView1.Columns[1].Name = "Category"; dataGridView1.Columns[2].Name = "Description"; //datagridview2 Columns dataGridView2.ColumnCount = 3; dataGridView2.Columns[0].Name = "ID"; dataGridView2.Columns[1].Name = "Category"; dataGridView2.Columns[2].Name = "Description"; dataGridView1.Rows.Add("1", "Computer", "Lorem Ipsum"); dataGridView1.Rows.Add("2", "Book", "Lorem Ipsum"); dataGridView1.Rows.Add("3", "Telephone", "Lorem Ipsum"); dataGridView1.Rows.Add("4", "Card Reader", "Lorem Ipsum"); dataGridView1.Rows.Add("5", "Modem", "Lorem Ipsum"); dataGridView1.Rows.Add("6", "USB", "Lorem Ipsum"); dataGridView1.Rows.Add("7", "Printer", "Lorem Ipsum"); dataGridView1.Rows.Add("8", "Scanner", "Lorem Ipsum"); } 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); } } } } |
Output: