tags:

views:

105

answers:

2

Hi, 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:

  1. Using the RowEnter and RowLeave 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.

  2. Using the RowStateChanged event. This works for multiple rows. However, the event gets fired event if the user scrolls through the 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.

Thanks :)

A: 

You can use your first method (row enter row leave) along with the SelectedRows property. Meaning, when you detect those events, and you need to calculate, instead of using the row from the event args, loop through the SelectedRows and get your total.

BFree
I can't do this, because I need to subtract amount from those records which were selected initially and are not selected now.
Rashmi Pandit
A: 

Found the soln. I can use RowStateChanged and run my only if StateChanged for the row is Selected.

i.e.

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
        }
Rashmi Pandit
soln... what a lazy way to write solution! :)
Chalkey
:) I don't usually do that ... but was in a real hurry yesterday
Rashmi Pandit