Click here to Skip to main content
15,895,849 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm writing a C# .NET Winforms app with a DataGridView that is loaded with data from a List<t>. When a row is deleted from the DataGridView, the default behavior is that the first row becomes the current row. I want to override that by making the row after the deleted row, if there is one, the new current row. Say I have a DataGridView with 5 rows and I want to delete Row #3. Row 4 then becomes the new Row #3, so I'd want the new Row #3 to become the current row. Or, if I delete Row #5, I want Row #4 to become the new current row. I'm using a global integer "currentindex" to set the current row. currentindex changes to the DataGridView's current row index when DataGridView_SelectionChanged event fires...
C#
private void DataGridView_SelectionChanged(object sender, EventArgs e)
        {
	        currentindex = DataGridView.CurrentRow.Index;
        }

Here's a block of code I wrote to update currentindex if it falls out of range after deleting a row...
C#
if (currentindex >= DataGridView.RowCount)
	     currentindex--;


NOTE: The DataGridView is not bound to the List<t>. I tried using a BindingList<t>, but I'll only have the same problem.

What I have tried:

I've tried putting this block of code in DataGridView_RowsRemoved, DataGridView_UserDeletingRow and DataGridView_UserDeletedRow, but Row #1 still ends up becoming the new current row after a row is deleted.
Posted
Updated 31-Jan-18 22:21pm
Comments
Karthik_Mahalingam 1-Feb-18 4:23am    
did you try with datatable?

Thanks for your suggestion, Richard, but that example doesn't address my situation. I want to override the DataGridView's default behavior when a row is deleted.

Thanks for your suggestion, Karthik, but using a DataTable won't help me override the DataGridView's default behavior when deleting a row.
 
Share this answer
 
Comments
Richard Deeming 1-Feb-18 15:29pm    
If you want to reply to a solution, click the "Have a Question or Comment?" button under the solution.

If you want to reply to a comment, click the "Reply" button next to the comment.

DO NOT post your reply as a "solution".
manic_drummer 2-Feb-18 17:54pm    
I didn't mean for my reply to be posted as a solution. Gimme a break!
Check this sample to see how to use the RowsRemoved event: DataGridView.RowsRemoved Event (System.Windows.Forms)[^].
 
Share this answer
 

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