DataGridView 捕获用户行选择 [英] DataGridView capturing user row selection
问题描述
我在处理 DataGridView
中的选择时遇到问题.我的网格视图包含一个金额列.表单上有一个文本框,应显示所选网格视图行的总数.因此,当用户选择/取消选择 gridview 行并相应地计算(加/减)数量时,我需要捕获事件.我找到了两种方法:
I am having trouble handling the selections in DataGridView
.
My grid view contains an amount column. There is a textbox on the form which should display the total amount of the selected grid view rows. Hence I need to capture events when the user selects/ deselects the gridview rows and calculate (add/ subtract) the amount accordingly. I have found two methods of doing it:
使用
RowEnter
和RowLeave
事件.当用户选择/取消选择单行时,这些工作正常.但是,当用户一次选择多行时,事件只会为最后一行触发.因此,从我的总金额中,只有最后一行的金额被添加/减去.从而使我的结果错误.
Using the
RowEnter
andRowLeave
events. These work fine when user selects/ deselects a single row. However, when the user is selecting multiple rows at one go, the event gets fired only for the last row. Hence, from my total amount only the amount in the last row gets added/ subtracted. Thus making my result erroneous.
使用 RowStateChanged
事件.这适用于多行.但是,如果用户滚动数据网格,则该事件会被触发.
Using the RowStateChanged
event.
This works for multiple rows. However, the event gets fired event if the user scrolls through the datagrid.
有没有人处理过这种情况.我想知道我应该使用哪个 datagrid 事件,以便我的代码仅在用户选择/取消选择包括多行的行时执行.
Has anyone handled such a scenario. I would like to know which datagrid event I should be using, so that my code executes only when user selects/ deselects rows including multiple rows.
推荐答案
找到了解决方案.我可以使用 RowStateChanged
并仅在 StateChanged
的行为 Selected
...
Found the solution. I can use RowStateChanged
and run my code only if StateChanged
for the row is Selected
...
private void dgridv_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e)
{
// For any other operation except, StateChanged, do nothing
if (e.StateChanged != DataGridViewElementStates.Selected) return;
// Calculate amount code goes here
}
这篇关于DataGridView 捕获用户行选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!