Hiding an ASPXGridView Delete button with HTMLRowCreated vs. CommandButtonInitialize

It's pretty typical in Administration forms to need to hide buttons on certain rows for various reasons. Particularly it is nice to hide the Delete button if in fact the row in question is being used in other places in the app. This is a nice feature to let the user know up front that the row in question is in use, rather than them trying to delete it and getting a foreign key related error after the fact.

For years now in DevExpress ASPxGridView's I have been handling this in the HtmlRowCreated event. And I have been doing it wrong.

Before:
protected void gridGiftCodes_HtmlRowCreated(object sender, DevExpress.Web.ASPxGridViewTableRowEventArgs e)
{
 if (e.RowType == GridViewRowType.Data){

  int commandColumnIndex = -1;

  //Find the command column
  commandColumnIndex = e.Row.Cells.Count-1;//assume it's the last visible colum

  //Get the command cell for this row
  GridViewTableCommandCell cell = e.Row.Cells[commandColumnIndex] as GridViewTableCommandCell;

  if (gridGiftCodes.GetRowValues(e.VisibleIndex, "InUseCount").ToString() != "0")
  {
   if (cell.Controls.Count == 3)
   {
    GridViewCommandColumnButtonControl btnDelete = cell.Controls[2] as GridViewCommandColumnButtonControl;
    btnDelete.Visible = false;
   }
  }
 }
}

Here is a better solution using the CommandButtonInitialize event that doesn't depend on your code-behind knowing the order of your command buttons.

After:
protected void gridGiftCodes_CommandButtonInitialize(object sender, ASPxGridViewCommandButtonEventArgs e)
{
 if (e.ButtonType == ColumnCommandButtonType.Delete)
 {
  if (gridGiftCodes.GetRowValues(e.VisibleIndex, "InUseCount").ToString() != "0")
  {
   e.Visible = false;
  }
 }
}

(Trying out a new code formatter, hilite.me - what do you think?)

More details on this approach can be found here:
https://www.devexpress.com/Support/Center/Example/Details/E366/how-to-customize-command-buttons-in-individual-rows


Comments

Popular posts from this blog

SQL 2005 SP4 and MSreplication_subscriptions

SQL Server Deadlocks - Easy Quick Start Guide