Not logged in - Login

XtraGrid keeping focus on same row after reload of data

The following example illustrates how to set the row focus of a grid back to the same row after the data has been reloaded.

// declare a variable to hold the ID of our current user
int? currentlySelectedUser = null;
// make sure the grid has some rows.
if (this.gridViewUsers.RowCount > 0)
{
   // get the User ID value from the row
   object oTemp = this.gridViewUsers.GetFocusedRowCellValue(this.lUserPK_colUser);
   // make sure we got back a value
   if (oTemp != null && oTemp != DBNull.Value)
   {
      // save the User ID to our local variable
      currentlySelectedUser = (int)oTemp;
   }
}



// load the grid data
this.gridUsers.DataSouce = this.GetOurData();


// set the focused row back to the user that had the focus before.
if (currentlySelectedUser.HasValue)
{
   // search for the User PK value in the grid
   int rowHandle = this.gridViewUsers.LocateByValue("lUserPK", currentlySelectedUser.Value);
   // was it found?
   if (rowHandle != DevExpress.XtraGrid.GridControl.InvalidRowHandle)
   {
      // set the focused row handle to the row that we found
      this.gridViewUsers.FocusedRowHandle = rowHandle;
   }
}