Windows Forms: Copy a Selected Row From one DataGridView to another DataGridView in C#

By FoxLearn 8/13/2017 8:32:10 AM   12.39K
Copy selected row from one DataGridView to another DataGridView in C#

Step 1Click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "CopyRowDataGridView" and then click OK

copy rows datagridviewStep 2: Design your form as below

copy rows datagridview in c#

Step 3: Create an EF Model, then select Category table from Northwind database

entity framework model

Step 4: Add code to handle your form as below

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 CopyRowDataGridView
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //Load data from sql database to DataGridView
            using (NorthwindEntities db = new NorthwindEntities())
            {
                categoryBindingSource.DataSource = db.Categories.ToList();
            }
        }

        private void btnLeft_Click(object sender, EventArgs e)
        {
            //Copy rows from DataGridView
            for(int i = dataGridViewRight.RowCount - 1; i >= 0; i--)
            {
                DataGridViewRow row = dataGridViewRight.Rows[i];
                if (Convert.ToBoolean(row.Cells["colRightSelected"].Value))
                {
                    categoryBindingSource.Add((Category)row.DataBoundItem);
                    categoryBindingSource1.RemoveAt(row.Index);
                }
            }
        }

        private void btnRight_Click(object sender, EventArgs e)
        {
            //Copy rows from DataGridView
            for(int i = dataGridViewLeft.RowCount - 1; i >= 0; i--)
            {
                DataGridViewRow row = dataGridViewLeft.Rows[i];
                if (Convert.ToBoolean(row.Cells["colLeftSelected"].Value))
                {
                    categoryBindingSource1.Add((Category)row.DataBoundItem);
                    categoryBindingSource.RemoveAt(row.Index);
                }
            }
        }
    }
}

VIDEO TUTORIALS