Monday, October 17, 2011

ASPxGridView GridViewCommandColumn delete button image at runtime with delete confirmation

 Scenario:
I have aspxGridView with list of items and i want to confirm from user before deletion
of a row/ record.

Solution:
There are two approach to achieve this target. one is
Using the in-built Delete button:  
GridViewCommandColumn.DeleteButton
GridViewCommandColumn commandColumn = new GridViewCommandColumn(); commandColumn.Width = new Unit("40"); commandColumn.ButtonType = ButtonType.Image; commandColumn.DeleteButton.Image.IsResourcePng = true; commandColumn.DeleteButton.Image.Url = "/images/common/manage_task.png";     commandColumn.DeleteButton.Visible = true; commandColumn.DeleteButton.Text = "Delete"; //Tooltip  gvMyDataGrid.Columns.Add(commandColumn); // add custom column to grid gvMyDataGrid.SettingsBehavior.ConfirmDelete = true;  // display popup confirmation upon clicking delete button gvMyDataGrid.SettingsText.ConfirmDelete = "Are you sure you want to delete this item?";  //Text you want to be displayed.  This can also be retrieved from the resource file


and another is:
Custom Button that you will create from scratch
GridViewCommandColumn commandColumn = new GridViewCommandColumn(); commandColumn.Width = new Unit("40"); commandColumn.ButtonType = ButtonType.Image;  GridViewCommandColumnCustomButton deleteButton = new GridViewCommandColumnCustomButton(); deleteButton.Image.IsResourcePng = true; deleteButton.Image.Url = "/images/common/manage_task.png"; deleteButton.Visibility = GridViewCustomButtonVisibility.AllDataRows; deleteButton.Text = "Delete"; deleteButton.ID = "cmdDelete";  commandColumn.CustomButtons.Add(deleteButton); // add custom button to new command column gvMyDataGrid.Columns.Add(commandColumn); //We need the next line of code to add the confirmation popup ourselves.   //Notice the 'cmdDelete' parameter which is the custom delete button's ID above. gvMyDataGrid.ClientSideEvents.CustomButtonClick =      "function (s, e) { if (e.buttonID == 'cmdDelete'){ "     +"e.processOnServer = confirm('Are you sure you want to delete this item?'); }}"; //confirm() method will return the user's selection:  true if OK, false if cancel.   //Therefore if return this value and set it to e.processOnServer,  //this will tell the button to not commit a callback if the user selects 'cancel'