How to get the Selected Row/s in a DevExpress.XtraGrid
This little helper class helps me to get the selected row/s of a GridView when I use the DevExpress.XtraGrid.
Usage is as Follows:
Say I have a Collection of ProductPrice objects, that is bound to a ObjectDataSource and in turn is bound to a GridView (gridViewActive) that is part of a GridControl (gridControl). (NB!! You will have to change the DomainObject to a base class or interface of your choice or remove it to get it to work for you)
All you do to get the selected row is:
| ProductItemPrice selectedPrice = GridHelper.GetSelectedRow<GridView, ProductItemPrice>(gridViewActive); |
or
| ProductItemPrice selectedPrice = GridHelper.GetSelectedRow<GridView, ProductItemPrice>(gridControl); |
Here is the GridHelper Code:
| /// <summary> |
| /// Helper for DevExpress XtraGrid |
| /// </summary> |
| public sealed class GridHelper |
| { |
| /// <summary> |
| /// Gets the selected row. |
| /// </summary> |
| /// <param name="gridView">The grid view.</param> |
| /// <returns></returns> |
| public static D GetSelectedRow<D>(ColumnView gridView) |
| where D : DomainObject |
| { |
| int[] selectedRows = gridView.GetSelectedRows(); |
| if (selectedRows.Length != 1) |
| return null; |
|
| D detail = gridView.GetRow(selectedRows[0]) as D; |
| if (detail == null) |
| return null; |
|
| return detail; |
| } |
|
| /// <summary> |
| /// Gets the selected row. |
| /// </summary> |
| /// <param name="gridControl">The grid control.</param> |
| /// <returns></returns> |
| public static D GetSelectedRow<D>(GridControl gridControl) |
| where D : DomainObject |
| { |
| ColumnView gridView = gridControl.GetViewAt(gridControl.PointToClient(Control.MousePosition)) as ColumnView; |
| if (gridView == null) |
| return null; |
|
| return GetSelectedRow<D>(gridView); |
| } |
|
| /// <summary> |
| /// Gets the selected rows. |
| /// </summary> |
| /// <param name="gridView">The grid view.</param> |
| /// <returns></returns> |
| public static L GetSelectedRows<L, D>(ColumnView gridView) |
| where L : IList, new() |
| where D : DomainObject |
| { |
| L list = new L(); |
|
| int[] selectedRows = gridView.GetSelectedRows(); |
| if (selectedRows.Length == 0) |
| return list; |
|
| foreach (int rowIndex in selectedRows) |
| { |
| D detail = gridView.GetRow(selectedRows[rowIndex]) as D; |
| if (detail == null) |
| continue; |
| list.Add(detail); |
| } |
|
| return list; |
| } |
| /// <summary> |
| /// Gets the selected rows. |
| /// </summary> |
| /// <param name="gridControl">The grid control.</param> |
| /// <returns></returns> |
| public static L GetSelectedRows<L, D>(GridControl gridControl) |
| where L : IList, new() |
| where D : DomainObject |
| { |
| ColumnView gridView = gridControl.GetViewAt(gridControl.PointToClient(Control.MousePosition)) as ColumnView; |
| if (gridView == null) |
| return new L(); |
|
| return GetSelectedRows<L, D>(gridView); |
| } |
| } |
|