Click here to Skip to main content
15,896,915 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hi.
I have a little problem.
I have a form with 2 datagridviews. I select rows to copy over to the new grid.

Here comes the problem. I also have a datetimepicker. In grid1 I have a column with a date. But when I past the copied files I like it to change that date to datetimepickers.
C#
try
{
    foreach (DataGridViewRow row in dataGridView1.SelectedRows)
    {      ((DataTable)dataGridView2.DataSource).ImportRow(((DataRowView)row.DataBoundItem).Row);
    }
    foreach (DataGridViewRow row in dataGridView2.Rows)
    {
        row.Cells[2].Value = dtp_Datum.Value.ToString();
    }
}

This code change every row. If I copy 2 rows and then change date, all rows in grid 2 get the latest changed date.
Posted
Updated 26-Apr-15 22:32pm
v2

1 solution

You need to only modify the added rows. Unfortunately, ImportRow does not return the newly created row, but according to the manual all new rows are added to the end of the datatable, so you can access them by index:

C#
int numberOfRowsToCopy = dataGridView1.SelectedRows.Count;
int numberOfExistingRows = dataGridView2.Rows.Count;

foreach(DataGridViewRow row in dataGridView1.SelectedRows)
{
    ((DataTable)dataGridView2.DataSource).ImportRow(((DataRowView) row.DataBoundItem).Row);
}

for(int i = 0; i < numberOfRowsToCopy; ++i)
{
    dataGridView2.Rows[numberOfExistingRows + i].Cells[2].Value = dtp_Datum.Value.ToString();
}
 
Share this answer
 
Comments
thaagaard elofsson 27-Apr-15 5:06am    
Thank you sooo much. It works great.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900