windowsforms-11863-controls-and-libraries-data-grid-examples-navigation-and-selection-how-to-obtain-and-modify-selected-rows.md
This example obtains selected rows and modifies their values in the “Discounted” column.
If data is sorted or filtered, changes made to one grid row can make other rows change their order and, as a result, their row handles. For this reason, you cannot access selected rows by their handles and process these rows right away. Instead, pass row handles retrieved by the ColumnView.GetSelectedRows method to the ColumnView.GetDataRow method. This allows you to access underlying data source objects (in this example, DataRows), save them to an array, and safely change their values afterwards.
Each row modification forces the Grid View to update itself. The example encloses the code within BaseView.BeginUpdate and BaseView.EndUpdate method calls to avoid excessive updates.
ArrayList rows = new ArrayList();
// Add the selected rows to the list.
Int32[] selectedRowHandles = gridView1.GetSelectedRows();
for (int i = 0; i < selectedRowHandles.Length; i++) {
int selectedRowHandle = selectedRowHandles[i];
if (selectedRowHandle >= 0)
rows.Add(gridView1.GetDataRow(selectedRowHandle));
}
try {
gridView1.BeginUpdate();
for (int i = 0; i < rows.Count; i++) {
DataRow row = rows[i] as DataRow;
// Change the field value.
row["Discontinued"] = true;
}
}
finally {
gridView1.EndUpdate();
}
Dim Rows As New ArrayList()
' Add the selected rows to the list.
Dim selectedRowHandles As Int32() = GridView1.GetSelectedRows()
Dim I As Integer
For I = 0 To selectedRowHandles.Length - 1
Dim selectedRowHandle As Int32 = selectedRowHandles(I)
If (selectedRowHandle >= 0) Then
Rows.Add(GridView1.GetDataRow(selectedRowHandle))
End If
Next
Try
GridView1.BeginUpdate()
For I = 0 To Rows.Count - 1
Dim Row As DataRow = CType(Rows(I), DataRow)
' Change the field value.
Row("Discontinued") = True
Next
Finally
GridView1.EndUpdate()
End Try