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

DoubleClick Cell edit

3 Answers 146 Views
Grid
This is a migrated thread and some comments may be shown as answers.
STEPHEN
Top achievements
Rank 1
STEPHEN asked on 24 Oct 2010, 03:53 PM
Can someone review my code. I have been struggling for the last few days.  Everything works except that it is not updating when I click the update. It posts back, but the values remain.

I am using this example as a template:  http://demos.telerik.com/aspnet-ajax/grid/examples/dataediting/clienteditbatchupdates/defaultcs.aspx

It probably has to do with namespace. I'm just learning and took it out.

<%@ Page Title="" Language="vb" AutoEventWireup="false" MasterPageFile="~/Site.Master" CodeBehind="test.aspx.vb" Inherits="WebDataInput.test" %>
<%@ Register assembly="Telerik.Web.UI" namespace="Telerik.Web.UI" tagprefix="telerik" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <telerik:RadCodeBlock ID="RadCodeBlock1" runat="server">
        <script type="text/javascript">
        <!--
            //Custom js code section used to edit records, store changes and switch the visibility of column editors
            //global variables for edited cell and edited rows ids
            var editedCell;
            var arrayIndex = 0;
            var editedItemsIds = [];
 
            function RowCreated(sender, eventArgs) {
                var dataItem = eventArgs.get_gridDataItem();
 
                //traverse the cells in the created client row object and attach dblclick handler for each of them
                for (var i = 1; i < dataItem.get_element().cells.length; i++) {
                    var cell = dataItem.get_element().cells[i];
                    if (cell) {
                        $addHandler(cell, "dblclick", Function.createDelegate(cell, ShowColumnEditor));
                    }
                }
            }
 
            //detach the ondblclick handlers from the cells on row disposing
            function RowDestroying(sender, eventArgs) {
                if (eventArgs.get_id() === "") return;
                var row = eventArgs.get_gridDataItem().get_element();
                var cells = row.cells;
                for (var j = 0, len = cells.length; j < len; j++) {
                    var cell = cells[j];
                    if (cell) {
                        $clearHandlers(cell);
                    }
                }
            }
 
            function RowClick(sender, eventArgs) {
                if (editedCell) {
                    //if the click target is table cell or span and there is an edited cell, update the value in it
                    //skip update if clicking a span that happens to be a form decorator element (having a class that starts with "rfd")
                    if ((eventArgs.get_domEvent().target.tagName == "TD") ||
                        (eventArgs.get_domEvent().target.tagName == "SPAN" && !eventArgs.get_domEvent().target.className.startsWith("rfd"))) {
                        UpdateValues(sender);
                        editedCell = false;
                    }
                }
            }
            function ShowColumnEditor() {
                editedCell = this;
 
                //hide text and show column editor in the edited cell
                var cellText = this.getElementsByTagName("span")[0];
                cellText.style.display = "none";
 
                //display the span which wrapps the hidden checkbox editor
                if (this.getElementsByTagName("span")[1]) {
                    this.getElementsByTagName("span")[1].style.display = "";
                }
                var colEditor = this.getElementsByTagName("input")[0] || this.getElementsByTagName("select")[0];
                //if the column editor is a form decorated select dropdown, show it instead of the original
                if (colEditor.className == "rfdRealInput" && colEditor.tagName.toLowerCase() == "select") colEditor = Telerik.Web.UI.RadFormDecorator.getDecoratedElement(colEditor);
                colEditor.style.display = "";
                colEditor.focus();
            }
            function StoreEditedItemId(editCell) {
                //get edited row key value and add it to the array which holds them
                var gridRow = $find(editCell.parentNode.id);
                var rowKeyValue = gridRow.getDataKeyValue("ContributionMasterID");
                Array.add(editedItemsIds, rowKeyValue);
            }
            function HideEditor(editCell, editorType) {
                //get reference to the label in the edited cell
                var lbl = editCell.getElementsByTagName("span")[0];
 
                switch (editorType) {
                    case "textbox":
                        var txtBox = editCell.getElementsByTagName("input")[0];
                        if (lbl.innerHTML != txtBox.value) {
                            lbl.innerHTML = txtBox.value;
                            editCell.style.border = "1px dashed";
 
                            StoreEditedItemId(editCell);
                        }
                        txtBox.style.display = "none";
                        break;
                    case "checkbox":
                        var chkBox = editCell.getElementsByTagName("input")[0];
                        if (lbl.innerHTML.toLowerCase() != chkBox.checked.toString()) {
                            lbl.innerHTML = chkBox.checked;
                            editedCell.style.border = "1px dashed";
 
                            StoreEditedItemId(editCell);
                        }
                        chkBox.style.display = "none";
                        editCell.getElementsByTagName("span")[1].style.display = "none";
                        break;
                    case "dropdown":
                        var ddl = editCell.getElementsByTagName("select")[0];
                        var selectedValue = ddl.options[ddl.selectedIndex].value;
                        if (lbl.innerHTML != selectedValue) {
                            lbl.innerHTML = selectedValue;
                            editCell.style.border = "1px dashed";
 
                            StoreEditedItemId(editCell);
                        }
                        //if the form decorator was enabled, hide the decorated dropdown instead of the original.
                        if (ddl.className == "rfdRealInput") ddl = Telerik.Web.UI.RadFormDecorator.getDecoratedElement(ddl);
                        ddl.style.display = "none";
                    default:
                        break;
                }
                lbl.style.display = "inline";
            }
            function UpdateValues(grid) {
                //determine the name of the column to which the edited cell belongs
                var tHeadElement = grid.get_element().getElementsByTagName("thead")[0];
                var headerRow = tHeadElement.getElementsByTagName("tr")[0];
                var colName = grid.get_masterTableView().getColumnUniqueNameByCellIndex(headerRow, editedCell.cellIndex);
 
                //based on the column name, extract the value from the editor, update the text of the label and switch its visibility with that of the column
                //column. The update happens only when the column editor value is different than the non-editable value. We also set dashed border to indicate
                //that the value in the cell is changed. The logic is isolated in the HideEditor js method
                switch (colName) {
                    case "PayDate":
                        HideEditor(editedCell, "textbox");
                        break;
                    case "Totals":
                        HideEditor(editedCell, "textbox");
                        break;
                    case "UnitPrice":
                        HideEditor(editedCell, "textbox");
                        break;
                    case "UnitsInStock":
                        HideEditor(editedCell, "dropdown");
                        break;
                    case "Discontinued":
                        HideEditor(editedCell, "checkbox");
                        break;
                    default:
                        break;
                }
            }
            function CancelChanges() {
                if (editedItemsIds.length > 0) {
                    $find("<%=RadAjaxManager1.ClientID %>").ajaxRequest("");
                }
                else {
                    alert("No pending changes to be discarded");
                }
                editedItemsIds = [];
            }
            function ProcessChanges() {
                //extract edited rows ids and pass them as argument in the ajaxRequest method of the manager
                if (editedItemsIds.length > 0) {
                    var Ids = "";
                    for (var i = 0; i < editedItemsIds.length; i++) {
                        Ids = Ids + editedItemsIds[i] + ":";
                    }
                    $find("<%=RadAjaxManager1.ClientID %>").ajaxRequest(Ids);
                }
                else {
                    alert("No pending changes to be processed");
                }
                editedItemsIds = [];
            }
            function RadGrid1_Command(sender, eventArgs) {
                //Note that this code has to be executed if you postback from external control instead from the grid (intercepting its onclientclick handler for this purpose),
                //otherwise the edited values will be lost or not propagated in the source
                if (editedItemsIds.length > 0) {
                    if (eventArgs.get_commandName() == "Sort" || eventArgs.get_commandName() == "Page" || eventArgs.get_commandName() == "Filter") {
                        if (confirm("Any unsaved edited values will be lost. Choose 'OK' to discard the changes before proceeding or 'Cancel' to abort the action and process them.")) {
                            editedItemsIds = [];
                        }
                        else {
                            //cancel the chosen action
                            eventArgs.set_cancel(true);
 
                            //process the changes
                            ProcessChanges();
                            editedItemsIds = [];
                        }
                    }
                }
            }
            window.onunload = function () {
                //this code should also be executed on postback from external control (which rebinds the grid) to process any unsaved data
                if (editedItemsIds.length > 0) {
                    if (confirm("Any unsaved edited values will be lost. Choose 'OK' to discard the changes before proceeding or 'Cancel' to abort the action and process them.")) {
                        editedItemsIds = [];
                    }
                    else {
                        //process the changes
                        ProcessChanges();
                        editedItemsIds = [];
                    }
                }
            };
     -->   
        </script>
    </telerik:RadCodeBlock>
    <telerik:RadFormDecorator ID="RadFormDecorator1" runat="server" DecoratedControls="Default,Select,Textbox"
        EnableRoundedCorners="false" />
    <telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">
        <AjaxSettings>
            <telerik:AjaxSetting AjaxControlID="RadGrid1">
                <UpdatedControls>
                    <telerik:AjaxUpdatedControl ControlID="RadGrid1" LoadingPanelID="RadAjaxLoadingPanel1" />
                    <telerik:AjaxUpdatedControl ControlID="RadInputManager1" />
                    <telerik:AjaxUpdatedControl ControlID="Label1" />
                </UpdatedControls>
            </telerik:AjaxSetting>
            <telerik:AjaxSetting AjaxControlID="RadAjaxManager1">
                <UpdatedControls>
                    <telerik:AjaxUpdatedControl ControlID="RadGrid1" LoadingPanelID="RadAjaxLoadingPanel1" />
                    <telerik:AjaxUpdatedControl ControlID="RadInputManager1" />
                    <telerik:AjaxUpdatedControl ControlID="Label1" />
                </UpdatedControls>
            </telerik:AjaxSetting>
        </AjaxSettings>
    </telerik:RadAjaxManager>
    <telerik:RadAjaxLoadingPanel ID="RadAjaxLoadingPanel1" runat="server" />
    <telerik:RadInputManager ID="RadInputManager1" EnableEmbeddedBaseStylesheet="false"
        Skin="" runat="server">
        <telerik:TextBoxSetting BehaviorID="StringBehavior" EmptyMessage="type here" />
        <telerik:NumericTextBoxSetting BehaviorID="CurrencyBehavior" EmptyMessage="type.."
            Type="Currency" Validation-IsRequired="true" MinValue="0" MaxValue="100000" />
        <telerik:NumericTextBoxSetting BehaviorID="NumberBehavior" EmptyMessage="type.."
            Type="Number" DecimalDigits="0" MinValue="0" MaxValue="100" />
    </telerik:RadInputManager>
    <telerik:RadGrid ID="RadGrid1" DataSourceID="SqlDataSource1" Width="97%" ShowStatusBar="True"
        AllowSorting="True" PageSize="15" GridLines="None" AllowPaging="True" runat="server"
        AutoGenerateColumns="False">
        <MasterTableView TableLayout="Fixed" DataKeyNames="ContributionMasterID" EditMode="InPlace"
            ClientDataKeyNames="ContributionMasterID" CommandItemDisplay="Bottom">
            <CommandItemTemplate>
                <div style="height: 30px; text-align: right;">
<asp:Image ID="imgCancelChanges" runat="server" ImageUrl="../Images/cancelEditGrid.gif"
AlternateText="Cancel changes" ToolTip="Cancel changes" Height="24px" Style="cursor: pointer;
margin: 2px 5px 0px 0px;" onclick="CancelChanges();" />
<asp:Image ID="imgProcessChanges" runat="server" ImageUrl="../Images/okEditGrid.gif"
AlternateText="Process changes" ToolTip="Process changes" Height="24px" Style="cursor: pointer;
margin: 2px 5px 0px 0px;" onclick="ProcessChanges();" />
                </div>
            </CommandItemTemplate>
            <Columns>
                
                <telerik:GridBoundColumn UniqueName="ContributionMasterID"
                    DataField="ContributionMasterID" HeaderText="ContributionMasterID"
                    ReadOnly="True" HeaderStyle-Width="25%"
                    SortExpression="ContributionMasterID" >
                    <HeaderStyle Width="25%"></HeaderStyle>
                 
                </telerik:GridBoundColumn>
                    <telerik:GridTemplateColumn HeaderText="Totals" HeaderStyle-Width="15%" UniqueName="Totals">
                    <ItemTemplate>
                        <asp:Label ID="lblTotals" runat="server" Text='<%# Eval("Totals", "{0:C}") %>' />
                        <asp:TextBox ID="txtTotals" runat="server" Text='<%# Eval("Totals", "{0:C}") %>' Style="display: none" />
                    </ItemTemplate>
                </telerik:GridTemplateColumn>
                            
            </Columns>
        </MasterTableView>
        <ClientSettings>
            <ClientEvents OnRowCreated="RowCreated" OnRowClick="RowClick" OnCommand="RadGrid1_Command"
                OnRowDestroying="RowDestroying" />
        </ClientSettings>
 
<HeaderContextMenu EnableAutoScroll="True"></HeaderContextMenu>
    </telerik:RadGrid>
    <br />
    <asp:Label ID="Label1" runat="server" EnableViewState="false" />
    <br />
     
    <asp:SqlDataSource ID="SqlDataSource1"
        ConnectionString="<%$ ConnectionStrings:RemoteSQLConnection %>" SelectCommand="SELECT ContributionMasterID, Totals FROM tblContributionMaster"
        runat="server"
        UpdateCommand="UPDATE tblContributionMaster SET Totals = @Totals WHERE (ContributionMasterID = @ContributionMasterID)">
        <UpdateParameters>
            <asp:Parameter Name="Totals"/>
            <asp:Parameter Name="ContributionMasterID"/>
         </UpdateParameters>
    </asp:SqlDataSource>
  
</asp:Content>

Code behind

Imports System
Imports Telerik.Web.UI
Imports System.Collections
 
Public Class test
    Inherits System.Web.UI.Page
 
    Private Sub SetMessage(ByVal message As String)
        Label1.Text = String.Format("<span>{0}</span>", message)
    End Sub
    Protected Sub RadGrid1_ItemCreated(ByVal sender As Object, ByVal e As GridItemEventArgs) Handles RadGrid1.ItemCreated
        If TypeOf e.Item Is GridDataItem Then
            Dim dataItem As GridDataItem = CType(e.Item, GridDataItem)
            '***************************************************************************************
            Dim txtBox As TextBox
            txtBox = CType(dataItem.FindControl("txtTotals"), TextBox)
            Dim currencySetting As NumericTextBoxSetting = DirectCast(RadInputManager1.GetSettingByBehaviorID("CurrencyBehavior"), NumericTextBoxSetting)
            currencySetting.TargetControls.Add(New TargetInput(txtBox.UniqueID, True))
 
        End If
    End Sub
    Protected Sub RadAjaxManager1_AjaxRequest(ByVal sender As Object, ByVal e As AjaxRequestEventArgs) Handles RadAjaxManager1.AjaxRequest
        If e.Argument = String.Empty Then
            RadGrid1.Rebind()
        End If
        Dim editedItemIds As String() = e.Argument.Split(":")
        Dim i As Integer
        For i = 0 To editedItemIds.Length - 2
            Dim contributionmasterid As String = editedItemIds(i)
            Dim updatedItem As GridDataItem = CType(RadGrid1.MasterTableView.FindItemByKeyValue("ContributionMasterID", "String"), GridDataItem)
            UpdateValues(updatedItem)
        Next
    End Sub
 
    Protected Sub UpdateValues(ByVal updatedItem As GridDataItem)
 
        Dim txtBox As TextBox
 
        txtBox = CType(updatedItem.FindControl("txtTotals"), TextBox)
        SqlDataSource1.UpdateParameters("Totals").DefaultValue = txtBox.Text
 
        ' Dim ddl As DropDownList = CType(updatedItem.FindControl("ddlUnitsInStock"), DropDownList)
        'SqlDataSource1.UpdateParameters("UnitsInStock").DefaultValue = ddl.SelectedValue
 
        'Dim chkBox As CheckBox = CType(updatedItem.FindControl("chkBoxDiscontinued"), CheckBox)
        'SqlDataSource1.UpdateParameters("Discontinued").DefaultValue = chkBox.Checked
 
        SqlDataSource1.UpdateParameters("ContributionMasterID").DefaultValue = updatedItem.GetDataKeyValue("ContributionMasterID").ToString()
        Try
            SqlDataSource1.Update()
        Catch ex As Exception
            SetMessage(Server.HtmlEncode("Unable to update Products. Reason: " + ex.StackTrace).Replace("'", "'").Replace(vbCrLf, "<br />"))
        End Try
        SetMessage("Product with ID: " & updatedItem.GetDataKeyValue("ContributionMasterID") & " updated")
 
    End Sub
End Class


3 Answers, 1 is accepted

Sort by
0
Iana Tsolova
Telerik team
answered on 27 Oct 2010, 03:07 PM
Hi STEPHEN,

Can you try setting the AllowAutomaticUpdates property of  the grid to true and see if it works as expected?


Kind regards,
Iana
the Telerik team
Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items
0
STEPHEN
Top achievements
Rank 1
answered on 27 Oct 2010, 04:15 PM
Thanks, but I figured it out.

I had a issue with the casting the type improperly and a few other things so the update didn't work properly.  But this type of functionality would be great out of the box. I know infragistics has a single click grid, so I think it is in demand.
0
Iana Tsolova
Telerik team
answered on 29 Oct 2010, 01:06 PM
Hello STEPHEN,

Thank you for your feedback. I will forward it to our developers for further consideration.

Kind regards,
Iana
the Telerik team
Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items
Tags
Grid
Asked by
STEPHEN
Top achievements
Rank 1
Answers by
Iana Tsolova
Telerik team
STEPHEN
Top achievements
Rank 1
Share this question
or