This is a migrated thread and some comments may be shown as answers.

confirming deletion of row(s) using radconfirm dialog

13 Answers 690 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Razak
Top achievements
Rank 2
Razak asked on 21 Nov 2011, 06:31 PM
I have a grid with delete button for each row and also in the commanditemtemplate. for these buttons, a confirmation dialog will popup when the user clicks on it. for the delete button in each row i can set the ConfirmationType to "RadWindow" and it does the job perfectly. But for the button in the commanditemtemplate, when i use the sample from the knowlegebase, it results in the rows' delete button to not working. I found that the javascript which is used to block the execution of the delete button in the commanditemtemplate while displaying the radconfirm dialog causes the delete button in each rows to fail when clicked. If I removed this script block, the delete button in each row shows the radconfirm dialog just fine. But of course, removing the script will cause the delete button in CommandItemTemplate to not wait for the user confirmation when clicked.

Here is the ASPX file used to reproduce this behavior:-
<telerik:RadScriptManager ID="RadScriptManager1" runat="server">
    <Scripts>
        <%--Needed for JavaScript IntelliSense in VS2010--%>
        <%--For VS2008 replace RadScriptManager with ScriptManager--%>
        <asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.Core.js" />
        <asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.jQuery.js" />
        <asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.jQueryInclude.js" />
    </Scripts>
</telerik:RadScriptManager>
<telerik:RadWindowManager ID="RadWindowManager1" runat="server" Style="z-index: 7500" />
 
<script type="text/javascript">
    //RADCONFIRM BLOCK THREAD SCRIPT
    //MAKE SURE THAT THE FOLLOWING SCRIPT IS PLACED AFTER THE RADWINDOWMANAGER DECLARATION
 
    //Replace old radconfirm with a changed version.  
    var oldConfirm = radconfirm;
    //TELERIK
    //window.radconfirm = function(text, mozEvent)
    //We will change the radconfirm function so it takes all the original radconfirm attributes
    window.radconfirm = function (text, mozEvent, oWidth, oHeight, callerObj, oTitle) {
        var ev = mozEvent ? mozEvent : window.event; //Moz support requires passing the event argument manually  
        //Cancel the event  
        ev.cancelBubble = true;
        ev.returnValue = false;
        if (ev.stopPropagation) ev.stopPropagation();
        if (ev.preventDefault) ev.preventDefault();
 
        //Determine who is the caller  
        callerObj = ev.srcElement ? ev.srcElement : ev.target;
 
        //Call the original radconfirm and pass it all necessary parameters  
        if (callerObj) {
            //Show the confirm, then when it is closing, if returned value was true, automatically call the caller's click method again.  
            var callBackFn = function (arg) {
                if (arg) {
                    callerObj["onclick"] = "";
                    if (callerObj.click) callerObj.click(); //Works fine every time in IE, but does not work for links in Moz  
                    else if (callerObj.tagName == "A") //We assume it is a link button!  
                    {
                        try {
                            eval(callerObj.href)
                        }
                        catch (e) { }
                    }
                }
            }
            //TELERIK
            //oldConfirm(text, callBackFn, 300, 100, null, null);      
            //We will need to modify the oldconfirm as well               
            oldConfirm(text, callBackFn, oWidth, oHeight, callerObj, oTitle);
        }
        return false;
    
</script>
 
<div>
    <telerik:RadGrid ID="RadGrid1" runat="server" AutoGenerateColumns="false" AllowMultiRowSelection="true">
        <ClientSettings EnableRowHoverStyle="true">
            <Selecting AllowRowSelect="true" EnableDragToSelectRows="false" />
        </ClientSettings>
        <MasterTableView CommandItemDisplay="Top">
            <CommandItemTemplate>
                <div>
                    <asp:LinkButton ID="LinkButton2" OnClientClick="return radconfirm('The selected application(s) will be deleted.\n\nClick OK to confirm.', event, null, null, '', 'Delete')"
                        runat="server" CommandName="DeleteSelected" CausesValidation="false">Delete</asp:LinkButton>   
                    <asp:LinkButton ID="LinkButton3" runat="server" CommandName="RebindGrid">Reload</asp:LinkButton>   
                </div>
            </CommandItemTemplate>
            <Columns>
                <telerik:GridClientSelectColumn HeaderStyle-Width="26px" ItemStyle-Width="26px" />
                <telerik:GridBoundColumn DataField="intcol" HeaderText="intcol" />
                <telerik:GridButtonColumn ButtonType="LinkButton" CommandName="Delete" ConfirmText="Delete?"
                    Text="Delete" ConfirmDialogType="RadWindow">
                </telerik:GridButtonColumn>
            </Columns>
        </MasterTableView>
    </telerik:RadGrid>
</div>

How do I make both set of delete buttons (in the CommandItemTemplate and in each row) to work as intended, ie. upon clicking, shows the radconfirn dialog for the user to confirm?

Thanks,

13 Answers, 1 is accepted

Sort by
0
Accepted
Marin
Telerik team
answered on 22 Nov 2011, 05:31 PM
Hi Abdul,

 Indeed the override of the radconfirm method does not work with the built in Delete buttons of the grid because they rely on the original implementation. One option could be to trigger the standard radconfirm function from the onclick event of the LinkButton and cancel the postback after the call. Then you can handle the user response in the callback function of the radconfirm and fire a custom grid command. Here is a sample code snippet illustrating this approach:

<CommandItemTemplate>
                        <div>
                            <asp:LinkButton ID="LinkButton2" OnClientClick="radconfirm('The selected application(s) will be deleted.\n\nClick OK to confirm.', callBackFn, null, null, '', 'Delete');return false;"
                                runat="server" CommandName="DeleteSelected" CausesValidation="false">Delete</asp:LinkButton>
                        </div>
                    </CommandItemTemplate>


function callBackFn(confirmed)
{
     if (confirmed)
     {
        $find('<%= RadGrid1.ClientID %>').get_masterTableView().fireCommand("DeleteSelected");
     }
}

protected void RadGrid1_ItemCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
        {
            if (e.CommandName=="DeleteSelected")
            {
                //process records
            }
        }



Regards,
Marin
the Telerik team
If you want to get updates on new releases, tips and tricks and sneak peeks at our product labs directly from the developers working on the RadControls for ASP.NET AJAX, subscribe to their blog feed now
0
Razak
Top achievements
Rank 2
answered on 22 Nov 2011, 11:42 PM
Thank you for your sample code Marin. It works!

However, unrelated to the original question, I realise that DeleteCommand event is triggered for every selected row?

I.e: If we selected 5 rows and click the delete button in CommandItemTemplate, the event got called 5 times, one for every rows. I prefer to iterate through RagGrid.SelectedItems in the first event trigger to get each row's datakeyvalue and construct the sql statement 'delete from .... where id in (..., ..., ...)' so the actual data deletion happens in 1 transaction.

Is there a way to specify the grid to only fire DeleteCommand only once ?
0
Marin
Telerik team
answered on 23 Nov 2011, 09:54 AM
Hello Abdul,

 The "DeleteSelected" command is a built-in command into the grid and it triggers the DeleteCommand event once for each selected row. Alternatively you trigger a custom command and intercept it in the ItemCommand event - which will be fired only once. There you can achieve the deleting of the items in one transaction.

$find('<%= RadGrid1.ClientID %>').get_masterTableView().fireCommand("DeleteSelected2");

protected void RadGrid1_ItemCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
        {
            if (e.CommandName=="DeleteSelected2")
            {
                //process records
            }
        }
protected void RadGrid1_DeleteCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
{
     //will not be fired for DeleteSelected2 command
}


Kind regards,
Marin
the Telerik team
If you want to get updates on new releases, tips and tricks and sneak peeks at our product labs directly from the developers working on the RadControls for ASP.NET AJAX, subscribe to their blog feed now
0
Razak
Top achievements
Rank 2
answered on 24 Nov 2011, 11:55 PM
Thanks for the tips Marin.
0
Steve
Top achievements
Rank 1
answered on 03 Mar 2012, 09:48 PM

Support Team,

I wanted to take this a step further.  I’m calling the radwindow from a button in a grid view, but when I go into the ItemCommand event,  the e.item.itemindex is always 0.

Here is my code:

javascript:

function btnDeletePersonInvolved_OnClientClick(confirmed) {

   try {

       if (confirmed) {

           $find('<%= rgPersonsInvolved.ClientID %>').get_masterTableView().fireCommand("DeletePerson");

       }

   }

   catch (e) {

       radalert(e.message, 450, 200, "Error", "");

   }

}

RadGrid:

<telerik:RadGrid ID="rgPersonsInvolved" runat="server"    DataSourceID="odsPersonsInvolved"

    OnItemCommand="rgPersonsInvolved_ItemCommand"

    AlternatingRowStyle-BackColor="#ECF3F9" RowStyle-BackColor="#FFFFFF"

    AutoGenerateColumns="False" AllowSorting="True"  Width="350px"

    Height="150px" CellSpacing="0" >

    <MasterTableView  TableLayout="Fixed"  AutoGenerateColumns="false" DataKeyNames="Personnel_ID"

    CommandItemDisplay="Top" ShowHeader="false" DataSourceID="odsPersonsInvolved" AllowSorting="true"  NoMasterRecordsText="No Records Found or an error occured." >

      <CommandItemSettings ShowAddNewRecordButton="false" />

     <Columns>

     <telerik:GridBoundColumn HeaderText="FullName" DataField="FullName"

           UniqueName="FullName"                                                        

     ShowFilterIcon="false" SortExpression="FullName" />

     <telerik:GridTemplateColumn>

         <ItemTemplate >

                 <asp:Button ID="btnDeletePersonsInvolved" runat="server" CssClass="CommandButton" Text="Delete" CommandName="DeletePerson" CausesValidation="false"

OnClientClick="radconfirm('The selected person will be deleted.\n\nClick OK to confirm.', btnDeletePersonInvolved_OnClientClick, null, null, '', 'Delete');return false;" />

</ItemTemplate>

</telerik:GridTemplateColumn>

       </Columns>

       </MasterTableView>

       <ClientSettings Selecting-AllowRowSelect="true" EnableRowHoverStyle="true">

       <Scrolling AllowScroll="true" SaveScrollPosition="true" UseStaticHeaders="true" />

       <Scrolling AllowScroll="true" SaveScrollPosition="true" UseStaticHeaders="true" /></ClientSettings>

</telerik:RadGrid>

Code Behind:

protected void rgPersonsInvolved_ItemCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)

        {

            IncidentDB objIncident;

            try

            {

                switch (e.CommandName)

                {

                    case "DeletePerson":

                        objIncident = new IncidentDB();

                        GridDataItem objItem = (GridDataItem)e.Item;

                        int intPersonnel_ID = Convert.ToInt32(objItem.GetDataKeyValue("Personnel_ID").ToString());

                        if (!objIncident.DeleteIncidentPersonnel(Convert.ToInt16(this.hdnIncident_ID.Value), intPersonnel_ID))

                        {

                            this.ShowMessage(objIncident.ErrorMessage, "Error");

                        }

                        else

                        {

                            this.rgPersonsInvolved.DataBind();

                        }

                        break;

                }

            }

            catch (Exception ex)

            {

                this.ShowMessage("Person Involved Item Command: " + ex.Message, "ERROR");

            }

            finally

            {

                objIncident = null;

            }

        }

Thanks in advance

Steve

0
Marin
Telerik team
answered on 07 Mar 2012, 04:53 PM
Hello Steve,

 When you fire a custom command from the client you should pass the ItemIndex as an argument and then access it on the server in the e.CommandArgument property:

try
                {
                    if (confirmed)
                    {
                        $find('<%= RadGrid1.ClientID %>').get_masterTableView().fireCommand("DeletePerson", 2);
                    }
                }

protected void rgPersonsInvolved_ItemCommand(object sender, GridCommandEventArgs e)
    {
        var itemIndex = int.Parse(e.CommandArgument.ToString());
    }

Hope this helps.All the best,
Marin
the Telerik team
If you want to get updates on new releases, tips and tricks and sneak peeks at our product labs directly from the developers working on the RadControls for ASP.NET AJAX, subscribe to their blog feed now.
0
Vignesh
Top achievements
Rank 1
answered on 18 Mar 2013, 10:45 AM
Hi princy

    Solution u gave in the last comment is working fine but instead of hard coding the value,
$find('<%= RadGrid1.ClientID %>').get_masterTableView().fireCommand("DeletePerson", 2);

 How can i pass DataKeyName as a argument for custom command.


0
Princy
Top achievements
Rank 2
answered on 18 Mar 2013, 12:18 PM
Hi,

You can set the ClientDataKeyNames and access from client-side as shown below.

ASPX:
<MasterTableView  ClientDataKeyNames="EmployeeID">

JavaScript:
var master = $find('<%= RadGrid1.ClientID %>').get_masterTableView();
alert(master.get_dataItems()[0].getDataKeyValue("EmployeeID"));

Thanks,
Princy.
0
Vignesh
Top achievements
Rank 1
answered on 19 Mar 2013, 05:56 AM
Hi princy,
    Thanks for your reply. The code which u gave in last comment is fine and correct too. But it not suits for my scenario. It always showing first records DataKeyName value. Here i'm pasting my code kindly verify it once. And let me know what i'm missing in it,
scenario is, Have to show radconfirm while clicking delete button and have to pass the datakeyname value to code behind to delete that particular record.
function callBackFn(confirmed) {
            if (confirmed) {
 
                var master = $find('<%= GridConsolidate.ClientID %>').get_masterTableView();
                alert(master.get_dataItems()[0].getDataKeyValue("TaskID"));
 
                //$find('<%= GridConsolidate.ClientID %>').get_masterTableView().fireCommand("DeleteSelected2", master );
            }
        }
<telerik:RadGrid ID="GridConsolidate" runat="server" AllowPaging="True" PageSize="20"
            AutoGenerateColumns="false" Width="100%" OnPageIndexChanged="GridConsolidate_PageIndexChanged"
            OnItemCreated="GridConsolidate_ItemCreated" OnItemCommand="GridConsolidate_ItemCommand"
            OnItemDataBound="GridConsolidate_ItemDataBound">
            <PagerStyle Mode="NumericPages"></PagerStyle>
            <MasterTableView EditMode="PopUp" DataKeyNames="TaskID" ClientDataKeyNames="TaskID" CommandItemDisplay="None">
                <Columns>
                    <telerik:GridBoundColumn DataField="TaskID" HeaderText="TaskID" Display="false" ReadOnly="True"
                        ItemStyle-Width="5%" SortExpression="TaskID" UniqueName="TaskID">
                    </telerik:GridBoundColumn>
                    <telerik:GridTemplateColumn UniqueName="TemplateDeleteColumn">
                        <ItemTemplate>
                        <asp:LinkButton ID="LinkButton2" OnClientClick="radconfirm('Are you sure, you want to delete?', callBackFn, null, null, '', 'Delete');return false;"
                                runat="server" CommandName="DeleteSelected2">Delete</asp:LinkButton>
                             
                        </ItemTemplate>
                    </telerik:GridTemplateColumn>
                </Columns>
            </MasterTableView>
        </telerik:RadGrid>
protected void GridConsolidate_ItemCommand(object sender, GridCommandEventArgs e)
        {
            if (e.CommandName == "DeleteSelected2")
            {
                var itemIndex = int.Parse(e.CommandArgument.ToString());
                GridDataItem item = GridConsolidate.Items[e.CommandArgument.ToString()];
                int Id = (int)item.GetDataKeyValue("TaskID");
                TaskBL t = new TaskBL();
                t.deletetask(Id);
                GridConsolidate.DataSource = t.getConsolidatedTasks();
                GridConsolidate.DataBind();
            }
        }
0
Princy
Top achievements
Rank 2
answered on 19 Mar 2013, 06:45 AM
Hi,

Try modifying the code as shown below.
JS:
var masterTable = $find('<%= RadGrid1.ClientID %>').get_masterTableView();
for (var i = 0; i < masterTable.get_dataItems().length; i++) {
 alert(master.get_dataItems()[i].getDataKeyValue("EmployeeID"));
}

Thanks,
Princy.
0
Vignesh
Top achievements
Rank 1
answered on 19 Mar 2013, 07:00 AM
Hi princy,

It displaying all the record values, But what i need is , exact row item's DataKeyName which i clicked.
0
Vignesh
Top achievements
Rank 1
answered on 19 Mar 2013, 11:49 AM
Hi princy,
   I found the way how to do. here my code.
Thanks for you help princy,
var dataKey;
function CellClick(index) {
            dataKey = index;
        }
 
 
        function callBackFn(confirmed) {
            if (confirmed) {
 
                var master = $find('<%= GridConsolidate.ClientID %>').get_masterTableView();
                $find('<%= GridConsolidate.ClientID %>').get_masterTableView().fireCommand("DeleteSelected2", dataKey);
            }
        }
<telerik:RadGrid ID="GridConsolidate" runat="server" AllowPaging="True" PageSize="20"
            AutoGenerateColumns="false" Width="100%" OnPageIndexChanged="GridConsolidate_PageIndexChanged"
            OnItemCreated="GridConsolidate_ItemCreated" OnItemCommand="GridConsolidate_ItemCommand"
            OnItemDataBound="GridConsolidate_ItemDataBound">
            <PagerStyle Mode="NumericPages"></PagerStyle>
            <MasterTableView EditMode="PopUp" DataKeyNames="TaskID" ClientDataKeyNames="TaskID" CommandItemDisplay="None">
                <Columns>
                    <telerik:GridBoundColumn DataField="TaskID" HeaderText="TaskID" Display="false" ReadOnly="True"
                        ItemStyle-Width="5%" SortExpression="TaskID" UniqueName="TaskID">
                    </telerik:GridBoundColumn>
<telerik:GridTemplateColumn UniqueName="TemplateDeleteColumn">
                        <ItemTemplate>
                        <asp:ImageButton ID="LinkButton2" OnClientClick="radconfirm('Are you sure, you want to delete?', callBackFn, null, null, '', 'Delete');return false;"
                                runat="server" CommandName="DeleteSelected2" ImageUrl="Files/new-delete.gif" />
                        </ItemTemplate>
                    </telerik:GridTemplateColumn>
                </Columns>
            </MasterTableView>
        </telerik:RadGrid>
protected void GridConsolidate_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item is GridDataItem)
            {
                foreach (GridColumn col in GridConsolidate.MasterTableView.Columns)
                {
                    GridDataItem dataItem = (GridDataItem)e.Item;
                    dataItem["TemplateDeleteColumn"].Attributes.Add("onclick", "CellClick('" + dataItem.ItemIndex + "','" + col.UniqueName + "');");
                }
            }
        }
 
        protected void GridConsolidate_ItemCommand(object sender, GridCommandEventArgs e)
        {
            if (e.CommandName == "DeleteSelected2")
            {
                var itemIndex = int.Parse(e.CommandArgument.ToString());
                GridDataItem item = GridConsolidate.Items[e.CommandArgument.ToString()];
                int Id = (int)item.GetDataKeyValue("TaskID");
                TaskBL t = new TaskBL();
                t.deletetask(Id);
                GridConsolidate.DataSource = t.getConsolidatedTasks();
                GridConsolidate.DataBind();
            }
        }
0
Sonny
Top achievements
Rank 1
answered on 24 Jun 2014, 09:08 PM
I solved this error by using asp:PlaceHolder around my Javascript code block, as per this article on StackOverflow:

http://stackoverflow.com/questions/4502552/the-controls-collection-cannot-be-modified-because-the-control-contains-code-blo
Tags
Grid
Asked by
Razak
Top achievements
Rank 2
Answers by
Marin
Telerik team
Razak
Top achievements
Rank 2
Steve
Top achievements
Rank 1
Vignesh
Top achievements
Rank 1
Princy
Top achievements
Rank 2
Sonny
Top achievements
Rank 1
Share this question
or