Reputation: 353
I have a DataGridView and a DataTable and i want to perform 2 step operation.1st is to copy selected row from DataGridView to DataTable for further processing,2nd step is to remove that row from DataGridView.
Note:I want to Delete Multiple rows one by one so each time i copy a row into DataTable it goes into next Datable Row index.
Here is code i am using to delete selected row from DataTable i want to know what is code for copying this selected row to DataTable.
private void btnDelete_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
try
{
dataGridView1.Rows.RemoveAt(row.Index);
}
catch (Exception)
{
throw;
}
}
}
Upvotes: 1
Views: 3611
Reputation: 726
DataRow row = ((DataRowView)row.DataBoundItem).Row
Using the above line of code you can read you data table row for each selected items.
to Copy
var datarow = ((DataRowView)row.DataBoundItem).Row;
newTable.Rows.Add(datarow.ItemArray);
full sample code
public partial class Form1 : Form
{
private DataTable table = new DataTable();
private DataTable newTable;
public Form1()
{
InitializeComponent();
table.Columns.AddRange(new DataColumn[] {
new DataColumn("id",typeof(int)),
new DataColumn("Desc",typeof(string))
});
newTable = table.Copy();
dataGridView1.DataSource = table;
dataGridView2.DataSource = newTable;
table.Rows.Add(1, "One");
table.Rows.Add(2, "Two");
table.Rows.Add(3, "Three");
table.Rows.Add(4, "Four");
table.Rows.Add(5, "Five");
}
private void btnDelete_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
try
{
var datarow = ((DataRowView)row.DataBoundItem).Row;
newTable.Rows.Add(datarow.ItemArray);
dataGridView1.Rows.RemoveAt(row.Index);
}
catch (Exception)
{
throw;
}
}
}
}
Upvotes: 2