Click here to Skip to main content
14,743,823 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I want to Move the checked row in gridview1 to gridview2 on a button click which is outside these gridviews and Delete the row from gridview1 which i just moved to Griview2.

What I have tried:

I have tried to look online multiple things for onbuttonclick event in code behind but it doesnt seems to work as i have just started working with c#. Please advice
Updated 11-Sep-20 1:14am
CHill60 10-Sep-20 8:48am
"but it doesnt seems to work" - what doesn't seem to work? You haven't shared with us the code that you have tried
User-14856258 10-Sep-20 9:31am
Hello Sir, Added what I have tried. Please check
CHill60 10-Sep-20 10:23am
If you are going to use databinding to populate the gridview then you will need to remove the row from the datasource and rebind it
User-14856258 10-Sep-20 10:37am
Didnt get it
Gerry Schmitz 10-Sep-20 13:59pm
"Moving" involves making a "copy" (of the data), and a delete (row) in the one grid and an add (row) in the other grid.

1 solution

I think I see what the problem is (that you still haven't described for us by the way).

You are stepping through the rows of your datagrid using foreach and attempting to rebind both data sources within that loop.

Use a for loop to step through your datatable backwards and do the rebinding outside the loop at the very end (for both GridViews).

Why use for instead of foreach - see the microsoft documentation[^]
Neither Delete nor Remove should be called in a foreach loop while iterating through a DataRowCollection object. Delete nor Remove modify the state of the collection.
Why step through backwards instead of forwards - if you want to delete rows 2 and 3 (say) from
1 - Row 1
2 - Row 2
3 - Row 3
4 - Row 4
after you delete row 2 the grid would look like
1 - Row 1
2 - Row 3
3 - Row 4
so if you try to delete what is now row 3 you would be deleting what was Row 4 instead. Incorrect.

Do it backwards and you delete Row 3 first to get
1 - Row 1
2 - Row 2
3 - Row 4
and Row 2 is exactly where it was when you started so you delete the correct rows

Why do the binding outside the loop - you are binding to the datatable so finish all your adjustments to that first then worry about what the UI will show.

Psuedo code snippet
for(int i=dtFirst.Rows.Count; i >=0; i--)
     // your checks etc
// After the loop has completed
// Rebind to the datatable and update viewstate before leaving the click event
GridView1.DataSource = dtFirst;

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