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

In insert/edit mode, grid is sorting on [ENTER] key

5 Answers 199 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Bryan Haas
Top achievements
Rank 1
Bryan Haas asked on 23 Sep 2009, 12:04 AM
So, I'm trying to set up my grid with keyboard shortcuts.  The following shortcuts work well: grid focus (ctrl-Y), item navigation (up/down keys), insert new item (ctrl-I), edit active item (enter key), and cancel insert/edit (esc key).  However, when an item is in insert/edit mode and I want to save the changes, I should be able to hit the enter key -- but, the grid sorts and I lose all my changes when I hit the enter key.  Why is the grid sorting???  I imagine that if I can solve the sorting issue, then the changes will be saved appropriately -- I hope.

Below is my grid markup...

            <telerik:RadGrid ID="grdCodeLists" runat="server" 
                GridLines="None" AllowPaging="true" PageSize="10" 
                AllowSorting="true" AllowFilteringByColumn="false" 
                AutoGenerateColumns="false" ShowGroupPanel="false" 
                AllowMultiRowEdit="false" AllowAutomaticDeletes="false" 
                AllowAutomaticInserts="false" AllowAutomaticUpdates="false" 
                OnNeedDataSource="grdCodeLists_NeedDataSource" 
                OnInsertCommand="grdCodeLists_InsertCommand" 
                OnUpdateCommand="grdCodeLists_UpdateCommand" 
                OnDeleteCommand="grdCodeLists_DeleteCommand"
                 
                <ClientSettings 
                    EnableRowHoverStyle="true" 
                    AllowKeyboardNavigation="true"
                    <Selecting AllowRowSelect="true" /> 
                    <KeyboardNavigationSettings 
                        EnableKeyboardShortcuts="true" 
                        AllowActiveRowCycle="true" 
                        FocusKey="Y" RebindKey="R" InitInsertKey="I" /> 
                    <ClientEvents OnRowSelected="RowSelected" /> 
                </ClientSettings> 
                 
                <SortingSettings 
                    SortedAscToolTip="Click to sort descending..." 
                    SortedDescToolTip="Click to sort ascending..." 
                    EnableSkinSortStyles="true" /> 
                     
                <PagerStyle 
                    AlwaysVisible="true" 
                    Mode="NextPrevAndNumeric" 
                    Position="Bottom" /> 
                                    
                <MasterTableView 
                    TableLayout="Fixed" 
                    EditMode="InPlace" 
                    CommandItemDisplay="None" 
                    DataKeyNames="CodeListID" 
                    AllowNaturalSort="false"
                    <SortExpressions> 
                        <telerik:GridSortExpression FieldName="CodeListName" SortOrder="Ascending" /> 
                    </SortExpressions> 
                    <Columns> 
                        <telerik:GridBoundColumn HeaderText="Code List ID" DataField="CodeListID" MaxLength="4" UniqueName="colID" /> 
                        <telerik:GridBoundColumn HeaderText="Code List Name" DataField="CodeListName" SortExpression="CodeListName" 
                            SortDescImageUrl="~/Images/icon_arrowDown.gif" SortAscImageUrl="~/Images/icon_arrowUp.gif" 
                            MaxLength="8" UniqueName="colName" /> 
                        <telerik:GridBoundColumn HeaderText="Code List Description" DataField="CodeListDescription" MaxLength="16" UniqueName="colDescription" /> 
                        <telerik:GridEditCommandColumn HeaderText="Edit" HeaderStyle-HorizontalAlign="Center" 
                            HeaderStyle-Width="65" ButtonType="ImageButton" EditImageUrl="~/Images/icon_edit.gif" 
                            UniqueName="colEdit" ItemStyle-HorizontalAlign="Center" /> 
                        <telerik:GridButtonColumn HeaderText="Delete" HeaderStyle-HorizontalAlign="Center" 
                            HeaderStyle-Width="65" ConfirmText="Delete Code List?" ConfirmDialogType="RadWindow" 
                            ConfirmTitle="Delete Code List" ButtonType="ImageButton" CommandName="Delete" 
                            UniqueName="colDelete" ImageUrl="~/Images/icon_delete.gif" ItemStyle-HorizontalAlign="Center" /> 
                    </Columns> 
                </MasterTableView>    
                              
            </telerik:RadGrid> 

5 Answers, 1 is accepted

Sort by
0
Bryan Haas
Top achievements
Rank 1
answered on 24 Sep 2009, 11:56 PM
So, I was able to finally get the keyboard support working, but it is not a straight forward solution.  I used bits and pieces of code from solutions in these forums, as well as some code of my own...

If anyone has time, including Telerik personnel, to take a look at my solution and provide some input, I would greatly appreciate it (I would have attached zipped files, but I couldn't figure out how to do that here)...

Here is the code behind:
using System; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
 
using System.Data; 
using System.Configuration; 
using System.Collections; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web.Security; 
using System.Web.UI.WebControls.WebParts; 
using System.Web.UI.HtmlControls; 
using Telerik.Web.UI; 
 
public partial class Default : System.Web.UI.Page  
    private const string _CODE_LISTS = "CodeLists"
 
    private ArrayList _CodeLists = null
    private ArrayList CodeLists 
    { 
        get 
        { 
            _CodeLists = (ArrayList)this.Page.Cache.Get(_CODE_LISTS); 
            if (_CodeLists == null) 
            { 
                _CodeLists = this.GetCodeLists(); 
                this.Page.Cache.Insert(_CODE_LISTS, _CodeLists); 
            } 
            return _CodeLists; 
        } 
    } 
 
    protected void Page_Load(object sender, EventArgs e) 
    { 
        if (!IsPostBack) { this.Page.Cache.Remove(_CODE_LISTS); } 
    } 
 
    protected void Page_PreRender(object sender, EventArgs e) 
    { 
    } 
 
    protected void grdCodeLists_NeedDataSource(object source, GridNeedDataSourceEventArgs e) 
    { 
        thisthis.grdCodeLists.DataSource = this.CodeLists; 
    } 
 
    protected void grdCodeLists_InsertCommand(object source, GridCommandEventArgs e) 
    { 
        CodeList newCodeList = this.GetCodeList(e); 
        if (!this.CodeLists.Contains(newCodeList)) { this.CodeLists.Add(newCodeList); } 
    } 
 
    protected void grdCodeLists_UpdateCommand(object source, GridCommandEventArgs e) 
    { 
        CodeList updateCodeList = this.GetCodeList(e); 
        int index = this.CodeLists.IndexOf(updateCodeList); 
        if (index >= 0) 
        { 
            this.CodeLists.RemoveAt(index); 
            this.CodeLists.Insert(index, updateCodeList); 
        } 
    } 
 
    protected void grdCodeLists_DeleteCommand(object source, GridCommandEventArgs e) 
    { 
        CodeList deleteCodeList = this.GetCodeList(e); 
        if (this.CodeLists.Contains(deleteCodeList)) { this.CodeLists.Remove(deleteCodeList); } 
    } 
 
    protected void grdCodeLists_ItemCreated(object sender, GridItemEventArgs e) 
    { 
        if (e.Item is GridDataItem && e.Item.IsInEditMode) 
        { 
            GridDataItem item = e.Item as GridDataItem; 
            List<GridColumn> editableColumns = item.OwnerTableView.RenderColumns.Select(c => c).Where 
                ( 
                    c => 
                    { 
                        if (c is GridEditableColumn) 
                        { 
                            GridEditableColumn column = (GridEditableColumn)c; 
                            return !column.ReadOnly && column.IsEditable; 
                        } 
                        return false; 
                    } 
                ).ToList(); 
 
            int lastIndex = editableColumns[editableColumns.Count - 1].OrderIndex; 
            editableColumns.ForEach 
                ( 
                    c => 
                    { 
                        TableCell editCell = (TableCell)item.EditManager.GetColumnEditor(c.UniqueName).ContainerControl; 
                        string script = String.Format("HandleKeyPress(this,event,'{0}','{1}','{2}');", 
                            item.OwnerTableView.ClientID, item.ItemIndex, (c.OrderIndex == lastIndex)); 
                        editCell.Attributes.Add("onkeydown", script); 
                    } 
                ); 
 
            TextBox txt = e.Item.FindControl("txtID") as TextBox; 
            if (txt != null) { txt.Focus(); } 
        } 
    } 
 
    private CodeList GetCodeList(GridCommandEventArgs e) 
    { 
        CodeList oCodeList = null
 
        try 
        { 
            GridEditableItem updateItem = e.Item as GridEditableItem; 
            Hashtable updateValues = new Hashtable(); 
            e.Item.OwnerTableView.ExtractValuesFromItem(updateValues, updateItem); 
 
            int ID = Convert.ToInt32(updateValues["CodeListID"]); 
            string Name = updateValues["CodeListName"].ToString(); 
            string Description = updateValues["CodeListDescription"].ToString(); 
 
            oCodeList = new CodeList(ID, Name, Description); 
        } 
        catch 
        { 
            oCodeList = null
        } 
 
        return oCodeList; 
    } 
 
    private ArrayList GetCodeLists() 
    { 
        ArrayList alItems = null
        string strItem = null
 
        try 
        { 
            alItems = new ArrayList(); 
            for (int index = 1; index <= 30; index++) 
            { 
                strItem = index.ToString(); 
                strItem = (index >= 10) ? "ITEM " + strItem : "ITEM 0" + strItem; 
                alItems.Add(new CodeList(index, strItem, "This is " + strItem)); 
            } 
        } 
        catch 
        { 
            alItems = null
        } 
 
        return alItems; 
    } 
 
public class CodeList 
    public int CodeListID { get; set; } 
    public string CodeListName { get; set; } 
    public string CodeListDescription { get; set; } 
 
    public CodeList() {} 
 
    public CodeList(int ID, string Name, string Description) 
    { 
        this.CodeListID = ID; 
        this.CodeListName = Name; 
        this.CodeListDescription = Description; 
    } 
 
    public override bool Equals(object o) 
    { 
        if (o is CodeList) 
        { 
            CodeList oCodeList = (CodeList)o; 
            return (this.CodeListID == oCodeList.CodeListID) || (this.CodeListName == oCodeList.CodeListName); 
        } 
        else 
        { 
            throw (new Exception("Object is not a CodeList")); 
        } 
    } 
 
    public override int GetHashCode() 
    { 
        return this.CodeListID.GetHashCode() ^ this.CodeListName.GetHashCode(); 
    } 
 


Here is the markup:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Default" %> 
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
 
<html xmlns="http://www.w3.org/1999/xhtml"
<head runat="server"
    <title></title
    <link rel="Stylesheet" href="Default.css" type="text/css" /> 
    <telerik:RadStyleSheetManager id="RadStyleSheetManager1" runat="server" /> 
</head> 
<body> 
    <form id="form1" runat="server"
     
        <telerik:RadScriptManager ID="RadScriptManager1" runat="server"
            <Scripts> 
                <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" /> 
            </Scripts> 
        </telerik:RadScriptManager> 
         
        <telerik:RadSkinManager ID="RadSkinManager1" Runat="server" Skin="Forest" /> 
         
        <telerik:RadAjaxManager ID="RadAjaxManager1" runat="server" /> 
         
        <telerik:RadCodeBlock ID="RadCodeBlock1" runat="server"
            <script type="text/javascript"
 
                var selectedRow = null
                var activeRow = null
 
                function ActiveRowChanged(sender, args) { 
                    // synchronize selected row with active row 
                    activeRow = args.get_id(); 
                    var grid = $find(sender.get_id()); 
                    var masterTable = grid.get_masterTableView(); 
 
                    if (activeRow != selectedRow) { 
                        selectedRow = activeRow
                        masterTable.selectItem($get(selectedRow)); 
                    } 
                } 
 
                function RowSelected(sender, args) { 
                    // synchronize active row with selected row 
                    selectedRow = args.get_id(); 
                    var grid = $find(sender.get_id()); 
 
                    if (selectedRow != activeRow) { 
                        activeRow = selectedRow
                        grid.set_activeRow($get(activeRow)); 
                    } 
                } 
 
                function PreventDefaultBehavior(e) { 
                    e.cancelBubble = true
                    e.returnValue = false
                    if (e.preventDefault) 
                        e.preventDefault(); 
                    if (e.stopPropagation) 
                        e.stopPropagation(); 
                } 
 
                function HandleKeyPress(cell, args, tableView, itemIndex, isLastColumn) { 
                    var e = args || window.event; 
                    if (e.keyCode == 13) { 
                        // enter pressed 
                        if (isLastColumn == "True") { 
                            PreventDefaultBehavior(e); 
 
                            // update/insert row on last item 
                            var table = $find(tableView); 
                            if (parseInt(itemIndex) >= 0) { 
                                table.updateItem(itemIndex); 
                            } 
                            else { 
                                table.insertItem(); 
                            } 
                        } 
                        e.keyCode = 9; // tab key 
                    } 
                    if (e.keyCode == 27) { 
                        // escape pressed 
                        PreventDefaultBehavior(e); 
 
                        // cancel update 
                        var table = $find(tableView); 
                        table.cancelUpdate(itemIndex); 
                    } 
                } 
                     
            </script> 
        </telerik:RadCodeBlock> 
         
        <div> 
         
            <table cellpadding="0" cellspacing="0" border="0" width="100%"
                <tr valign="middle"
                    <td align="left"
                        <h1>Code Lists</h1> 
                    </td> 
                </tr> 
            </table> 
             
            <telerik:RadAjaxPanel ID="RadAjaxPanel1" runat="server" > 
                <telerik:RadGrid ID="grdCodeLists" runat="server" 
                    GridLines="None" AllowPaging="true" PageSize="10" 
                    AllowSorting="true" AllowFilteringByColumn="false" 
                    AutoGenerateColumns="false" ShowGroupPanel="false" 
                    AllowMultiRowEdit="false" AllowAutomaticDeletes="false" 
                    AllowAutomaticInserts="false" AllowAutomaticUpdates="false" 
                    OnNeedDataSource="grdCodeLists_NeedDataSource" 
                    OnInsertCommand="grdCodeLists_InsertCommand" 
                    OnUpdateCommand="grdCodeLists_UpdateCommand" 
                    OnDeleteCommand="grdCodeLists_DeleteCommand" 
                    OnItemCreated="grdCodeLists_ItemCreated"
                     
                    <ClientSettings 
                        EnableRowHoverStyle="true" 
                        AllowKeyboardNavigation="true"
                        <Selecting AllowRowSelect="true" /> 
                        <KeyboardNavigationSettings 
                            EnableKeyboardShortcuts="true" 
                            AllowActiveRowCycle="true" 
                            FocusKey="Z" RebindKey="R" InitInsertKey="I" /> 
                        <ClientEvents 
                            OnRowSelected="RowSelected" 
                            OnActiveRowChanged="ActiveRowChanged" /> 
                    </ClientSettings> 
                     
                    <SortingSettings 
                        SortedAscToolTip="Click to sort descending..." 
                        SortedDescToolTip="Click to sort ascending..." 
                        EnableSkinSortStyles="true" /> 
                         
                    <PagerStyle 
                        AlwaysVisible="true" 
                        Mode="NextPrevAndNumeric" 
                        Position="Bottom" /> 
                                        
                    <MasterTableView 
                        AccessKey="X" 
                        TableLayout="Fixed" 
                        EditMode="InPlace" 
                        CommandItemDisplay="Top" 
                        InsertItemPageIndexAction="ShowItemOnCurrentPage" 
                        DataKeyNames="CodeListID" 
                        AllowNaturalSort="false"
                        <CommandItemSettings AddNewRecordText="Add Code List" /> 
                        <SortExpressions> 
                            <telerik:GridSortExpression FieldName="CodeListName" SortOrder="Ascending" /> 
                        </SortExpressions> 
                        <Columns> 
                            <telerik:GridTemplateColumn HeaderText="Code List ID" DataField="CodeListID" UniqueName="colID" > 
                                <ItemTemplate > 
                                    <asp:Label ID="lblID" runat="server" ><%# Eval("CodeListID")%></asp:Label> 
                                </ItemTemplate> 
                                <EditItemTemplate > 
                                    <asp:TextBox ID="txtID" runat="server" Text='<%# Bind("CodeListID") %>' MaxLength="4" /> 
                                </EditItemTemplate> 
                            </telerik:GridTemplateColumn>                                 
                            <telerik:GridBoundColumn HeaderText="Code List Name" DataField="CodeListName" 
                                SortExpression="CodeListName" MaxLength="8" UniqueName="colName" /> 
                            <telerik:GridBoundColumn HeaderText="Code List Description" DataField="CodeListDescription" 
                                MaxLength="16" UniqueName="colDescription" /> 
                            <telerik:GridEditCommandColumn HeaderText="Edit" HeaderStyle-HorizontalAlign="Center" 
                                HeaderStyle-Width="65" ButtonType="ImageButton" 
                                UniqueName="colEdit" ItemStyle-HorizontalAlign="Center" /> 
                            <telerik:GridClientDeleteColumn HeaderText="Delete" HeaderStyle-HorizontalAlign="Center" 
                                HeaderStyle-Width="65" ConfirmText="Delete Code List?" ConfirmDialogType="RadWindow" 
                                ConfirmTitle="Delete Code List" ButtonType="ImageButton" ItemStyle-HorizontalAlign="Center" />                        
                        </Columns> 
                    </MasterTableView>    
                                  
                </telerik:RadGrid> 
            </telerik:RadAjaxPanel> 
             
        </div> 
         
    </form> 
</body> 
</html> 
 

0
Tsvetoslav
Telerik team
answered on 26 Sep 2009, 06:13 AM
Hello Bryan,

I ran your sample without the work-around client methods and the grid does not sort on ENTER. However, the item not being updated on ENTER being hit is implemented by design due to the existence of various scenarios in which there might be AutoPostback set to true for the various controls, some custom handling of the key pressed event, etc.

You can change this behavior by adding the following modification to the following grid's internal method:

            Telerik.Web.UI.RadGrid.prototype._canHandleKeyboardAction = function(e) {  
                
                var keyCode = e.keyCode || e.charCode;  
                
                if ((keyCode == 32 || keyCode == 13) && this.ClientSettings.KeyboardNavigationSettings.EnableKeyboardShortcuts) {  
                    var target = Telerik.Web.UI.Grid.GetCurrentElement(e);  
                    var isClientSelectCheckBox = (target.tagName.toLowerCase() == "input" &&  
                                                      target.type.toLowerCase() == "checkbox" &&  
                                                     (target.id && target.id.indexOf("SelectCheckBox") != -1));  
                      
                    if (target.tagName.toLowerCase() == "textarea") {  
                        return false;  
                    }  
                }  
                return true;  
            } 

I hope this helps.


Regards,
Tsvetoslav
the Telerik team

Instantly find answers to your questions on the new Telerik Support Portal.
Watch a video on how to optimize your support resource searches and check out more tips on the blogs.
0
momentum
Top achievements
Rank 1
answered on 19 Oct 2009, 03:11 AM
Hi, would it be possible to supply this code in VB? I am looking to have my insert/update submit when enter key pressed.

Thanks

Brian
0
Princy
Top achievements
Rank 2
answered on 19 Oct 2009, 04:46 AM
Hello Brian,

You can make use of any of the following code conversion tools to convert necessary code snippets from vb to c# or vice versa:
Telerik code converter
conversion tool

Thanks
Princy.
0
momentum
Top achievements
Rank 1
answered on 13 May 2010, 01:02 AM
Hi Princy, i have converted and had a look at the code and it is a little more complicated of a solution then I am looking for. Do you know how I can get information (ie binded data values) out of:

1) The row being dragged
2) The row above where the row was dropped (if not dropped at the top of the grid)
3) The row below where the row was dropped (if not dropped at the bottom of the grid)

Thanks
Tags
Grid
Asked by
Bryan Haas
Top achievements
Rank 1
Answers by
Bryan Haas
Top achievements
Rank 1
Tsvetoslav
Telerik team
momentum
Top achievements
Rank 1
Princy
Top achievements
Rank 2
Share this question
or