删除行时如何覆盖datagridview默认行为? [英] How do I override datagridview default behavior when removing row?
问题描述
我正在编写一个带有DataGridView的C#.NET Winforms应用程序,该应用程序加载了来自List< t>的数据。从DataGridView中删除行时,默认行为是第一行成为当前行。我想通过在删除的行之后创建一个行(如果有的话)来覆盖新的当前行。假设我有一个5行的DataGridView,我想删除第3行。第4行然后成为新的第3行,所以我希望新的第3行成为当前行。或者,如果我删除第5行,我希望第4行成为新的当前行。我正在使用全局整数currentindex来设置当前行。当DataGridView_SelectionChanged事件触发时,currentindex更改为DataGridView的当前行索引...
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...
private void DataGridView_SelectionChanged(object sender, EventArgs e)
{
currentindex = DataGridView.CurrentRow.Index;
}
这是我写的一段代码,如果删除行后超出范围,我会更新currentindex ...
Here's a block of code I wrote to update currentindex if it falls out of range after deleting a row...
if (currentindex >= DataGridView.RowCount)
currentindex--;
注意:DataGridView未绑定到List< t>。我尝试使用BindingList< t>,但我只会遇到同样的问题。
我尝试了什么:
我已经尝试将这个代码块放在DataGridView_RowsRemoved,DataGridView_UserDeletingRow和DataGridView_UserDeletedRow中,但是在删除行之后,第1行仍然会成为新的当前行。
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.
推荐答案
检查此示例以了解如何使用RowsRemoved事件: DataGridView.RowsRemoved事件(System.Windows.Forms) [ ^ ]。
Check this sample to see how to use the RowsRemoved event: DataGridView.RowsRemoved Event (System.Windows.Forms)[^].
感谢你的建议,理查德,但这个例子并没有解决我的情况。我想在删除行时覆盖DataGridView的默认行为。
感谢您的建议,Karthik,但使用DataTable无法帮助我覆盖DataGridView的默认值删除行时的行为。
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.
这篇关于删除行时如何覆盖datagridview默认行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!