Refer following sample. Here I have shown how to copy checked Rows from DataGridView to DataTable and then bind the DataTable to another DataGridView.
Database
I have made use of the following table Customers with the schema as follows.
I have already inserted few records in the table.
Download SQL file
Form Design
Namespaces
using System.Data;
using System.Data.SqlClient;
Code
public partial class Form1 : Form
{
private const string ConnectionString = @"Data Source=.\SQL2014;Initial Catalog=AjaxSamples;Integrated Security = true";
public Form1()
{
InitializeComponent();
this.BindGrid();
}
private void BindGrid()
{
using (SqlConnection con = new SqlConnection(ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("SELECT CustomerId, Name, Country FROM Customers", con))
{
cmd.CommandType = CommandType.Text;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
dataGridView1.DataSource = dt;
}
}
}
}
//Add a CheckBox Column to the DataGridView at the first position.
DataGridViewCheckBoxColumn checkBoxColumn = new DataGridViewCheckBoxColumn();
checkBoxColumn.HeaderText = "";
checkBoxColumn.Width = 30;
checkBoxColumn.Name = "checkBoxColumn";
dataGridView1.Columns.Insert(0, checkBoxColumn);
}
private void btnGet_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("CustomerId");
dt.Columns.Add("Name");
dt.Columns.Add("Country");
foreach (DataGridViewRow row in dataGridView1.Rows)
{
bool isSelected = Convert.ToBoolean(row.Cells["checkBoxColumn"].Value);
if (isSelected)
{
dt.Rows.Add(row.Cells[1].Value, row.Cells[2].Value, row.Cells[3].Value);
}
}
dataGridView2.DataSource = dt;
}
}
Screenshot