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:
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.
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.
To get the selected rows in a DataGridView controlUse the SelectedRows property. To enable users to select rows, you must set the SelectionMode property to FullRowSelect or RowHeaderSelect.
When a row is selected in a GridView control, use the SelectedRow property to retrieve the GridViewRow object that represents that row. This is the same as retrieving the GridViewRow object at the index specified by the SelectedIndex property from the Rows collection.
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
}
I use SelectionChanged event or CellValueChanged event:
dtGrid.SelectionChanged += DataGridView_SelectionChanged;
this.dtGrid.DataSource = GetListOfEntities;
dtGrid.CellValueChanged += DataGridView_CellValueChanged;
private void DataGridView_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
DataGridViewRow row = dtGrid.Rows[e.RowIndex];
SetRowProperties(row);
}
private void DataGridView_SelectionChanged(object sender, EventArgs e)
{
var rowsCount = dtGrid.SelectedRows.Count;
if (rowsCount == 0 || rowsCount > 1) return;
var row = dtGrid.SelectedRows[0];
if (row == null) return;
ResolveActionsForRow(row);
}
I think you can consider the SelectionChanged event:
private void DataGridView1_SelectionChanged(object sender, EventArgs e) {
textbox1.Text = DataGridView1.SelectedRows.Count.ToString();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With