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

Detect Current Column/Keypress During Edit

8 Answers 552 Views
Grid
This is a migrated thread and some comments may be shown as answers.
J
Top achievements
Rank 1
J asked on 15 Apr 2013, 08:12 PM
I am trying to detect when a user presses the Tab key inside the last column of my inline edit form.  When they press Tab on the last column, I want the grid to create a new row, put it into edit mode, and move the cursor there.

I can already do this with the Enter key but I cannot figure out how to tell when the Tab key is pressed in the last column and only when in the last column.

Any ideas?  I know I can add character/key code 9 for Tab but I can't tell which column I'm in when it detects it.  I'm sure it's probably something simple that I've overlooked.

The last column's definition:

<telerik:GridBoundColumn ConvertEmptyStringToNull="False" DataField="Email" FilterControlAltText="Filter Email column"
    HeaderText="Email" SortExpression="Email" UniqueName="Email" EmptyDataText=""
    ColumnEditorID="txtGridEdit_Email" ShowSortIcon="False">
    <HeaderStyle Width="100px" Wrap="False" HorizontalAlign="Left" CssClass="grid-header" VerticalAlign="Top"/>
    <ItemStyle HorizontalAlign="Left" Width="100%" VerticalAlign="Top" />
</telerik:GridBoundColumn>

The column editor:

<telerik:GridTextBoxColumnEditor ID="txtGridEdit_Email" runat="server" TextBoxStyle-Width="99%"  />


The javascript I'm using on the Keypress event (client side):

/// <summary>
/// Handles the client side KeyPress event of the Athletes grid.
/// </summary>
function OnKeyPress(sender, args) {
    //Check for the Enter/Tab key being pressed
    if ((args._domEvent.charCode == 13) || (args.get_keyCode() == 13)) {
        //If currently editing a row, commit the changes and stop the editing
        if (rowEditedItem) {
            bHasChanges = false;
            $find(sAthleteGridID).get_masterTableView().updateItem(rowEditedItem);
        }
    }
    else if ((args.get_keyCode() == 27) || (args._domEvent.charCode == 27)) //Check for the Esc key being press
    {
        $find(sAthleteGridID).get_masterTableView().fireCommand("CancelAll", ""); //Cancel any editing activities in the grid
        $find(sAthleteGridID).get_masterTableView().clearSelectedItems(); //De-select any rows
    }
}

8 Answers, 1 is accepted

Sort by
0
J
Top achievements
Rank 1
answered on 16 Apr 2013, 05:38 PM
I created the following javascript function which properly detects the Tab key being pressed:

/// <summary>
/// Handles the client side KeyPress event of the Athletes grid.
/// </summary>
function GridColKeyPress(sender, args) {
    var ret_bHandlePress;
    var keyPressed;
 
    ret_bHandlePress = true;
    args = (args || window.event);
    keyPressed = (args.which || args.keyCode);
 
    //Check for the Tab key being pressed
    if ((keyPressed == 9) && !args.shiftKey && !args.ctrlKey && !args.altKey) {
        //If currently editing a row, commit the changes and stop the editing
        if (rowEditedItem) {
            bHasChanges = false;
            $find(sAthleteGridID).get_masterTableView().updateItem(rowEditedItem);
            $find(sAthleteGridID).get_masterTableView().fireCommand("InitInsert", "");
        }
 
        ret_bHandlePress = false;
        args.handled = true;
        args.preventDefault();
    }
 
    return ret_bHandlePress;
}

Added the following to my grid's ItemDataBound event:

protected void grdAthletes_ItemDataBound(object sender, GridItemEventArgs e)
{
    Control ctrlFields = null;
 
    try
    {
        //Some controls don't load the values into the custom editor's automatically so force the values through
        if (e.Item.IsInEditMode)
        {
            ctrlFields = ((GridEditableItem)e.Item)["Email"].Controls[0];
            ((TextBox)ctrlFields).TabIndex = 56;
            ((TextBox)ctrlFields).Attributes.Add("OnKeyPress", "return GridColKeyPress('" + ctrlFields.ClientID + "', event)");
            ((TextBox)ctrlFields).Attributes.Add("OnKeyDown", "return GridColKeyPress('" + ctrlFields.ClientID + "', event)");
        }
    }
    catch (Exception ex)
    {
        System.Diagnostics.Debug.Print("Error: " + ex.ToString());
        Exceptions.ProcessModuleLoadException(this, ex);
    }
}

This properly detects the Tab key being pressed, BUT if I leave the javascript as-is, the Tab key basically gets disabled while in that field.  I can remove the 'handled', 'preventDefault', and return True instead, which allows tabbing in/out of the field but neither approach allows the 'InitInsert' event to fire (I also tried using 'AddNewRow' instead of 'InitInsert' but no change).

Any ideas?  It's SOOOOO close, just need a way to tell the grid from the client side that it needs to fire off the add new row event just like the 'Add' button from the command bar does.
0
J
Top achievements
Rank 1
answered on 16 Apr 2013, 06:19 PM
I got it working.  I removed the lines from the javascript that caused the return value to be false and then fixed my other functions which were causing my failure to detect a row was being edited/inserted and then other lines in my code behind which were meant to prevent trying to save rows with insufficient data was causing the insert command to not get fired properly.

Also, the Tab key can only be detected by using the OnKeyDown event and not the OnKeyPress.

Thanks for ... well ...  o_o

=P
0
J
Top achievements
Rank 1
answered on 16 Apr 2013, 07:41 PM
I spoke too soon.  It looked like it was working due to a glitch on my part.

I cannot get the client side code to create a new row and put it into edit mode.

Any ideas?
0
Angel Petrov
Telerik team
answered on 18 Apr 2013, 11:22 AM
Hi Juan,

The functionality desired can be achieved using the fireCommand client-side method. In order to open the insert from you will first have to obtain a reference to the MasterTableView and then fire an appropriate command, in the particular case InitInsert. This is also demonstrated in the code snippet below:
function InitInserForGrid()
      {
          var grid = $find("<%=RadGrid1.ClientID %>");
          grid.get_masterTableView().fireCommand("InitInsert", "");
      }

Regards,
Angel Petrov
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
J
Top achievements
Rank 1
answered on 18 Apr 2013, 03:43 PM
Yes, I'm aware of that.  The value of 'sAthletesGrid' is populated using:

var sAthleteGridID = "<%=grdAthletes.ClientID %>";

For completeness' sake, here's the entire javascript right now so you can see all the related pieces:

<telerik:RadCodeBlock ID="codScriptManager" runat="server">
    <script type="text/javascript" language="javascript">
        var bHasChanges = false;
        var colUIInputItems = null;
        var colDropdownLists = null;
        var rowEditedItem = null;
        var sAthleteGridID = "<%=grdAthletes.ClientID %>";
 
        function btnFindMember_ClientClick(sender) {
            var btnFind = document.getElementById("<%=btnFindMember.ClientID %>");
 
            if (btnFind != null) {
                btnFind.disabled = true;
                btnFind.className = "btn-clear-member";
                btnFind.value = "Searching...";
            }
 
            return true;
        }
 
        /// <summary>
        /// Checks if the currently focused item is inside the grid.
        /// </summary>
        function IsItemInsideGrid()
        {
            var ret_bIsInGrid = false;
            var objCurItem = document.activeElement;
            var sObjectChain = "";
 
            if (objCurItem != null) {
                sObjectChain = objCurItem.id;
 
                //Keep looking at the object's parent object until the grid or top-most parent is found
                while (objCurItem.parentNode)
                {
                    objCurItem = objCurItem.parentNode;
 
                    if ((objCurItem != null)  && (objCurItem.id.length > 0))
                    {
                        sObjectChain += (" -> " + objCurItem.id);
 
                        if (objCurItem.id.indexOf(sAthleteGridID) > -1)
                        {
                            ret_bIsInGrid = true;
                            break;
                        }
                    }
                }
 
    //          if (sObjectChain.length > 0)
    //              alert(sObjectChain);
            }
 
            if (!ret_bIsInGrid) {
                if (rowEditedItem == null)
                    GetCurrentEditRow();
 
                //If currently editing a row, commit the changes and stop the editing
                if (rowEditedItem) {
                    bHasChanges = false;
                    $find(sAthleteGridID).get_masterTableView().updateItem(rowEditedItem);
 
                    $find(sAthleteGridID).get_masterTableView().fireCommand("CancelAll", ""); //Cancel any editing activities in the grid
                    $find(sAthleteGridID).get_masterTableView().clearSelectedItems(); //De-select any rows
                }
            }
 
            return ret_bIsInGrid;
        }
 
        /// <summary>
        /// Handles the client side events when the athletes grid loses focus.
        /// </summary>
        function grdAthletes_LostFocus(sender, eventArgs) {
            setTimeout(IsItemInsideGrid, 50);
    //      if (!IsItemInsideGrid())
    //      {
    //          //If currently editing a row, commit the changes and stop the editing
    //          if (rowEditedItem)
    //          {
    //              bHasChanges = false;
    //              $find(sAthleteGridID).get_masterTableView().updateItem(rowEditedItem);
 
 
    //              $find(sAthleteGridID).get_masterTableView().fireCommand("CancelAll", ""); //Cancel any editing activities in the grid
    //              $find(sAthleteGridID).get_masterTableView().clearSelectedItems(); //De-select any rows
    //          }
    //      }
        }
 
        /// <summary>
        /// Handles the client side RowClick event of the Athletes grid.
        /// </summary>
        function RowClick(sender, eventArgs) {
            //            if (rowEditedItem && bHasChanges) {
            //                bHasChanges = false;
            //                $find(sAthleteGridID).get_masterTableView().updateItem(rowEditedItem);
            //            }
        }
 
        /// <summary>
        /// Handles the client side RowDblClick event of the Athletes grid.
        /// </summary>
        function RowDblClick(sender, eventArgs)
        {
            rowEditedItem = eventArgs.get_itemIndexHierarchical();
            $find(sAthleteGridID).get_masterTableView().editItem(rowEditedItem);
        }
 
        /// <summary>
        /// Handles the client side GridCommand event of the Athletes grid.
        /// </summary>
        function GridCommand(sender, args) {
            if (!args.get_commandName().contains("Edit") && !args.get_commandName().contains("Insert") && !args.get_commandName().contains("AddNew"))
                rowEditedItem = null;
        }
 
        /// <summary>
        /// Gets the current grid item that is being edited/inserted.
        /// </summary>
        function GetCurrentEditRow() {
            var rowEdit;
            var rowInsert;
 
            rowEdit = $find(sAthleteGridID).get_masterTableView().get_editItems();
 
            if (rowEdit != null)
                rowEditedItem = rowEdit[0];
            else {
                rowInsert = $find(sAthleteGridID).get_masterTableView().get_editItems();
 
                if (rowInsert != null)
                    rowEditedItem = rowInsert[0];
 
            }
 
            if (rowEditedItem == null)
                rowEditedItem = $find(sAthleteGridID).get_masterTableView().get_itemIndexHierarchical();
 
            rowEdit = null;
            rowInsert = null;
        }
 
        /// <summary>
        /// Handles the client side GridCreated event of the Athletes grid.
        /// </summary>
        function GridCreated(sender, eventArgs) {
            var objGrid = sender.get_element();
            var arrUIObjects = [];
            var lowerType = null;
 
            colUIInputItems = objGrid.getElementsByTagName("input");
 
            //Set up change tracking for the input controls in the grid
            for (var iInputItems = 0; iInputItems < colUIInputItems.length; iInputItems++) {
                lowerType = colUIInputItems[iInputItems].type.toLowerCase();
 
                if ((lowerType == "hidden") || (lowerType == "button"))
                    continue;
 
                if ((colUIInputItems[iInputItems].id.indexOf("PageSizeComboBox") == -1) && (colUIInputItems[iInputItems].type.toLowerCase() != "checkbox"))
                    Array.add(arrUIObjects, colUIInputItems[iInputItems]);
 
                colUIInputItems[iInputItems].onchange = TrackChanges;
            }
 
            colDropdownLists = objGrid.getElementsByTagName("select");
 
            //Set up change tracking for the drop down controls in the grid
            for (var iDropDowns = 0; iDropDowns < colDropdownLists.length; iDropDowns++)
                colDropdownLists[iDropDowns].onchange = TrackChanges;
 
            setTimeout(function () { if (arrUIObjects[0]) arrUIObjects[0].focus(); }, 100);
        }
 
        /// <summary>
        /// Handles the client side RowSelected event of the Athletes grid.
        /// </summary>
        function RowSelected(sender, eventArgs) {
//          if (rowEditedItem == null)
//              GetCurrentEditRow();
 
            //If editing a row and changes are pending, commit the changes and stop the editing
            if (bHasChanges && rowEditedItem) {
                bHasChanges = false;
                $find(sAthleteGridID).get_masterTableView().updateItem(rowEditedItem);
            }
        }
 
        /// <summary>
        /// Handles the client side Change event for controls in the Athletes grid.
        /// </summary>
        function TrackChanges(e) {
            bHasChanges = true;
        }
 
        /// <summary>
        /// Handles the client side KeyPress event of the Athletes grid.
        /// </summary>
        function OnKeyPress(sender, args) {
            var ret_bHandlePress;
            var keyPressed;
 
            ret_bHandlePress = true;
            args = (args || window.event);
 
            if (!args.shiftKey && !args.ctrlKey && !args.altKey) {
 
                keyPressed = (args.which || args.keyCode || args._domEvent.charCode || args.get_keyCode());
 
                //Check for the Enter/Tab key being pressed
                if (keyPressed == 13) {
//                  ret_bHandlePress = false;
                    //              if (rowEditedItem == null)
                    //                  GetCurrentEditRow();
 
                    //If currently editing a row, commit the changes and stop the editing
                    if (rowEditedItem) {
                        bHasChanges = false;
                        $find(sAthleteGridID).get_masterTableView().updateItem(rowEditedItem);
                    }
                }
                else if (keyPressed == 27) //Check for the Esc key being press
                {
//                  ret_bHandlePress = false;
                    $find(sAthleteGridID).get_masterTableView().fireCommand("CancelAll", ""); //Cancel any editing activities in the grid
                    $find(sAthleteGridID).get_masterTableView().clearSelectedItems(); //De-select any rows
                }
            }
 
            return ret_bHandlePress;
        }
 
        /// <summary>
        /// Handles the client side KeyPress event of the Athletes grid.
        /// </summary>
        function GridColKeyPress(sender, args) {
            var ret_bHandlePress;
            var keyPressed;
 
            ret_bHandlePress = true;
            args = (args || window.event);
 
            if (!args.shiftKey && !args.ctrlKey && !args.altKey) {
                keyPressed = (args.which || args.keyCode || args._domEvent.charCode || args.get_keyCode());
 
                //Check for the Tab key being pressed
                if ((keyPressed == 9)) {
                    //              if (rowEditedItem == null)
                    //                  GetCurrentEditRow();
 
                    //If currently editing a row, commit the changes and stop the editing
                    if (rowEditedItem) {
                        bHasChanges = false;
                        $find(sAthleteGridID).get_masterTableView().updateItem(rowEditedItem);
                    }
 
                    $find(sAthleteGridID).get_masterTableView().fireCommand("InitInsert", "");
                }
            }
 
            return ret_bHandlePress;
        }
    </script>
</telerik:RadCodeBlock>


The grid's definition:

<telerik:RadGrid ID="grdAthletes" runat="server" AllowAutomaticDeletes="True" AllowSorting="True"
                        PageSize="12" AutoGenerateColumns="False" OnNeedDataSource="grdAthletes_NeedDataSource"
                        OnItemCommand="grdAthletes_ItemCommand" OnPreRender="grdAthletes_PreRender" OnUpdateCommand="grdAthletes_UpdateCommand"
                        Width="100%" OnDeleteCommand="grdAthletes_DeleteCommand" OnEditCommand="grdAthletes_EditCommand"
                        OnItemDataBound="grdAthletes_ItemDataBound" ShowStatusBar="True" AllowAutomaticInserts="True"
                        AllowAutomaticUpdates="True" OnItemCreated="grdAthletes_ItemCreated" Skin="Metro"
                        BorderStyle="None" CellSpacing="0" GridLines="None" ForeColor="White" BackColor="Transparent"
                        ShowFooter="True" TabIndex="17">
                        <ValidationSettings ValidationGroup="AthletesGrid" />
                        <ClientSettings AllowKeyboardNavigation="True">
                            <Selecting AllowRowSelect="True" />
                            <KeyboardNavigationSettings AllowSubmitOnEnter="True" AllowActiveRowCycle="True" />
                            <Scrolling AllowScroll="True" UseStaticHeaders="True" SaveScrollPosition="true" />
                            <ClientEvents OnKeyPress="OnKeyPress" OnRowSelected="RowSelected" OnRowClick="RowClick"
                                OnRowDblClick="RowDblClick" OnGridCreated="GridCreated" OnCommand="GridCommand" />
                            <Resizing ShowRowIndicatorColumn="False" />
                        </ClientSettings>
                        <AlternatingItemStyle BackColor="LightGray" BorderStyle="None" ForeColor="Black" />
                        <MasterTableView NoMasterRecordsText="No athletes to display." EditMode="InPlace"
                            CommandItemDisplay="Bottom" BorderStyle="None" BackColor="Transparent" ShowFooter="False">
                            <HeaderStyle BorderStyle="None" Font-Bold="True" Font-Size="Medium" ForeColor="White"
                                Height="48px" HorizontalAlign="Left" VerticalAlign="Middle" Wrap="True" />
                            <CommandItemStyle CssClass="rgCommandRow" />
                            <FooterStyle BorderStyle="None" CssClass="grid-footer" />
                            <CommandItemTemplate>
                                <div align="left">
                                    <asp:LinkButton ID="btnAddNew" runat="server" CommandName="AddNewRow" TabIndex="18" CausesValidation="false">
                                        <asp:Image runat="server" ImageUrl="~/Images/112_Plus_Green_32x42_72.png" CssClass="GridCommandBarItemImage" AlternateText="Add Athlete" /> Add Athlete</asp:LinkButton>  
                                </div>
                            </CommandItemTemplate>
                            <CommandItemSettings ExportToPdfText="Export to PDF" ShowRefreshButton="False" AddNewRecordText="Add Athlete">
                            </CommandItemSettings>
                            <RowIndicatorColumn FilterControlAltText="Filter RowIndicator column">
                                <HeaderStyle Width="20px"></HeaderStyle>
                            </RowIndicatorColumn>
                            <ExpandCollapseColumn FilterControlAltText="Filter ExpandColumn column">
                                <HeaderStyle Width="20px"></HeaderStyle>
                            </ExpandCollapseColumn>
                            <EditFormSettings EditFormType="Template">
                                <EditColumn FilterControlAltText="Filter EditCommandColumn column" CancelImageUrl="Cancel.gif"
                                    InsertImageUrl="Update.gif" UpdateImageUrl="Update.gif" Visible="true" Display="true">
                                </EditColumn>
                            </EditFormSettings>
                            <ItemStyle BackColor="White" BorderStyle="None" ForeColor="Black" />
                            <AlternatingItemStyle BackColor="LightGray" BorderStyle="None" ForeColor="Black" />
                            <EditItemStyle BackColor="Gainsboro" BorderStyle="None" />
                            <PagerStyle PageSizeControlType="RadComboBox"></PagerStyle>
                            <Columns>
                                <telerik:GridBoundColumn ConvertEmptyStringToNull="False" DataField="RowCount" EmptyDataText="" FilterControlAltText="Filter RowCount column" HeaderText="" SortExpression="RowCount" UniqueName="RowCount" ReadOnly="true">
                                    <HeaderStyle Wrap="False" HorizontalAlign="Left" Width="24px" CssClass="grid-header grid-header-first" />
                                    <ItemStyle HorizontalAlign="Left" VerticalAlign="Middle" Width="24px" />
                                </telerik:GridBoundColumn>
                                <telerik:GridBoundColumn DataField="FirstName" HeaderText="Name<br />First"
                                    UniqueName="FirstName" ConvertEmptyStringToNull="False" SortExpression="FirstName"
                                    EmptyDataText="" ColumnEditorID="txtGridEdit_FirstName" ColumnGroupName="AthleteName"
                                    ShowSortIcon="False">
                                    <ColumnValidationSettings EnableRequiredFieldValidation="True">
                                        <RequiredFieldValidator ForeColor="Red" ErrorMessage="* Required"></RequiredFieldValidator>
                                    </ColumnValidationSettings>
                                    <HeaderStyle Wrap="False" HorizontalAlign="Left" Width="70px" CssClass="grid-header" VerticalAlign="Middle"/>
                                    <ItemStyle HorizontalAlign="Left" Width="100%" VerticalAlign="Top" />
                                </telerik:GridBoundColumn>
                                <telerik:GridBoundColumn DataField="MiddleName" HeaderText="<br/>M" UniqueName="MiddleName"
                                    ConvertEmptyStringToNull="False" EmptyDataText="" SortExpression="MiddleName"
                                    ColumnEditorID="txtGridEdit_MiddleName" ColumnGroupName="AthleteName" ShowSortIcon="False">
                                    <HeaderStyle Wrap="False" HorizontalAlign="Left" Width="50px" CssClass="grid-header" VerticalAlign="Middle"/>
                                    <ItemStyle HorizontalAlign="Left" Width="100%" VerticalAlign="Top" />
                                </telerik:GridBoundColumn>
                                <telerik:GridBoundColumn DataField="LastName" HeaderText="<br/>Last" UniqueName="LastName"
                                    ConvertEmptyStringToNull="False" SortExpression="LastName" EmptyDataText="" ColumnEditorID="txtGridEdit_LastName"
                                    ColumnGroupName="AthleteName" ShowSortIcon="False">
                                    <ColumnValidationSettings EnableRequiredFieldValidation="True">
                                        <RequiredFieldValidator ForeColor="Red" ErrorMessage="* Required"></RequiredFieldValidator>
                                    </ColumnValidationSettings>
                                    <HeaderStyle Wrap="False" HorizontalAlign="Left" Width="70px" CssClass="grid-header" VerticalAlign="Middle"/>
                                    <ItemStyle HorizontalAlign="Left" Width="100%" VerticalAlign="Top" />
                                </telerik:GridBoundColumn>
                                <telerik:GridTemplateColumn HeaderText="Gender" SortExpression="Gender" UniqueName="Gender"
                                    DataField="Gender" FilterControlAltText="Filter Gender column"
                                    ShowSortIcon="False">
                                    <ItemTemplate>
                                        <%# DataBinder.Eval(Container.DataItem, "Gender") %></ItemTemplate>
                                    <EditItemTemplate>
    <%--                                    <asp:DropDownList ID="ddlGender" runat="server">
                                            <Items>
                                                <asp:ListItem Text="Female" Value="Female" />
                                                <asp:ListItem Text="Male" Value="Male" Selected="True" />
                                            </Items>
                                        </asp:DropDownList>--%>
                                        <telerik:RadDropDownList ID="ddlGender" runat="server" Width="100%" TabIndex="19">
                                            <Items>
                                                <telerik:DropDownListItem Text="Female" Value="Female" />
                                                <telerik:DropDownListItem Text="Male" Value="Male" Selected="true" />
                                            </Items>
                                        </telerik:RadDropDownList>
                                    </EditItemTemplate>
                                    <HeaderStyle Wrap="False" HorizontalAlign="Left" Width="85px" CssClass="grid-header" VerticalAlign="Top" />
                                    <ItemStyle HorizontalAlign="Left" Width="90%" VerticalAlign="Top" />
                                </telerik:GridTemplateColumn>
                                <telerik:GridDateTimeColumn ConvertEmptyStringToNull="False" DataField="DoB" FilterControlAltText="Filter DoB column"
                                    HeaderText="Date of Birth" SortExpression="DoB" UniqueName="DoB" DataFormatString="{0:M/d/yy}"
                                    DataType="System.DateTime" EmptyDataText="" ColumnEditorID="dtGridEdit_DoB" ShowFilterIcon="False"
                                    EditDataFormatString="M/d/yy" MaxLength="8" ShowSortIcon="False">
                                    <ColumnValidationSettings EnableRequiredFieldValidation="True">
                                        <RequiredFieldValidator ForeColor="Red" ErrorMessage="* Max age exceeded" ID="valReqDoB"></RequiredFieldValidator>
                                    </ColumnValidationSettings>
                                    <HeaderStyle Wrap="False" HorizontalAlign="Left" Width="106px" CssClass="grid-header" VerticalAlign="Top" />
                                    <ItemStyle Width="100%" HorizontalAlign="Left" VerticalAlign="Top"></ItemStyle>
                                </telerik:GridDateTimeColumn>
                                <telerik:GridMaskedColumn ConvertEmptyStringToNull="False" DataField="ZipCode" DataFormatString="{0:#####}"
                                    FilterControlAltText="Filter ZipCode column" HeaderText="Zip Code" Mask="#####"
                                    SortExpression="ZipCode" UniqueName="ZipCode" EmptyDataText="" ShowSortIcon="False">
                                    <ColumnValidationSettings EnableRequiredFieldValidation="True">
                                        <RequiredFieldValidator ForeColor="Red" ErrorMessage="* Required"></RequiredFieldValidator></ColumnValidationSettings>
                                    <HeaderStyle Wrap="False" HorizontalAlign="Left" Width="80px" CssClass="grid-header" VerticalAlign="Top" />
                                    <ItemStyle Width="100%" HorizontalAlign="Left" VerticalAlign="Top"></ItemStyle>
                                </telerik:GridMaskedColumn>
                                <telerik:GridBoundColumn ConvertEmptyStringToNull="False" DataField="Email" FilterControlAltText="Filter Email column"
                                    HeaderText="Email" SortExpression="Email" UniqueName="Email" EmptyDataText=""
                                    ColumnEditorID="txtGridEdit_Email" ShowSortIcon="False">
                                    <HeaderStyle Width="100px" Wrap="False" HorizontalAlign="Left" CssClass="grid-header" VerticalAlign="Top"/>
                                    <ItemStyle HorizontalAlign="Left" Width="100%" VerticalAlign="Top" />
                                </telerik:GridBoundColumn>
                                <telerik:GridBoundColumn ConvertEmptyStringToNull="False" DataField="UniqueID" EmptyDataText=""
                                    FilterControlAltText="Filter column column" HeaderText="Unique ID" SortExpression="UniqueID"
                                    UniqueName="UniqueID" Visible="False">
                                    <HeaderStyle CssClass="grid-header" />
                                    <ItemStyle HorizontalAlign="Left" VerticalAlign="Top" />
                                </telerik:GridBoundColumn>
                                <telerik:GridButtonColumn ButtonType="ImageButton" CommandName="Edit" FilterControlAltText="Filter EditColumn column"
                                    ImageUrl="Images/126_Edit_16x16_72.png" Text="" UniqueName="EditColumn" Resizable="false"
                                    ConfirmDialogType="RadWindow">
                                    <HeaderStyle Wrap="False" HorizontalAlign="Left" Width="24px" CssClass="grid-header">
                                    </HeaderStyle>
                                    <ItemStyle Width="100%" HorizontalAlign="Right" VerticalAlign="Top" />
                                </telerik:GridButtonColumn>
                                <telerik:GridButtonColumn ButtonType="ImageButton" CommandName="Delete" FilterControlAltText="Filter DeleteColumn column"
                                    ImageUrl="Images/305_Close_16x16_72.png" Text="" UniqueName="DeleteColumn" Resizable="false"
                                    ConfirmText="Remove this athelete?" ConfirmDialogType="RadWindow" ConfirmTitle="Remove"
                                    ShowInEditForm="True">
                                    <HeaderStyle Wrap="False" HorizontalAlign="Left" Width="24px" CssClass="grid-header grid-header-last">
                                    </HeaderStyle>
                                    <ItemStyle Width="100%" HorizontalAlign="Right" VerticalAlign="Top" />
                                </telerik:GridButtonColumn>
                            </Columns>
                        </MasterTableView><EditItemStyle BackColor="Gainsboro" BorderStyle="None" />
                        <FooterStyle BorderStyle="None" />
                        <HeaderStyle BorderStyle="None" Height="48px" HorizontalAlign="Left" VerticalAlign="Middle" />
                        <CommandItemStyle CssClass="rgCommandRow" />
                        <ItemStyle BackColor="White" BorderStyle="None" ForeColor="Black" />
                        <PagerStyle PageSizeControlType="RadComboBox"></PagerStyle>
                        <SelectedItemStyle BorderStyle="None" />
                        <FilterMenu EnableImageSprites="False">
                        </FilterMenu>
                        <HeaderContextMenu CssClass="GridContextMenu GridContextMenu_Default">
                        </HeaderContextMenu>
                    </telerik:RadGrid>
                    <telerik:GridTextBoxColumnEditor ID="txtGridEdit_FirstName" runat="server" TextBoxStyle-Width="99%" />
                    <telerik:GridTextBoxColumnEditor ID="txtGridEdit_MiddleName" runat="server" TextBoxStyle-Width="99%" />
                    <telerik:GridTextBoxColumnEditor ID="txtGridEdit_LastName" runat="server" TextBoxStyle-Width="99%" />
                    <telerik:GridDropDownListColumnEditor ID="cmbGridEdit_Gender" runat="server" DropDownStyle-Width="100px" />
                    <telerik:GridDateTimeColumnEditor runat="server" ID="dtGridEdit_DoB" TextBoxStyle-Width="99%"  />
                    <telerik:GridTextBoxColumnEditor ID="txtGridEdit_Email" runat="server" TextBoxStyle-Width="99%"  />

Grid related events from the code behind:

#region Grid events
 
protected void grdAthletes_PreRender(object sender, EventArgs e)
{
    try
    {
        CheckAtheleteTeamSize();
    }
    catch (Exception ex)
    {
        System.Diagnostics.Debug.Print("Error: " + ex.ToString());
        Exceptions.ProcessModuleLoadException(this, ex);
    }
}
 
protected void grdAthletes_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
{
    try
    {
        UpdateGridRowCounts();
 
        //Provide the current data for the grid to use
        grdAthletes.DataSource = _propsSettings.Records;
    }
    catch (Exception ex)
    {
        System.Diagnostics.Debug.Print("Error: " + ex.ToString());
        Exceptions.ProcessModuleLoadException(this, ex);
    }
}
 
protected void grdAthletes_UpdateCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
{
    this.UpdateGridItem((GridEditableItem)e.Item, true);
}
 
/// <summary>
/// Commits the specified row data to the underlying data source.
/// </summary>
/// <param name="UpdatedRow">The updated row data to commit.</param>
/// <param name="StartNewRow">Indicates if a new row should be created if the specified row is successfully updated.</param>
private void UpdateGridItem(GridEditableItem UpdatedRow, bool StartNewRow)
{
    Hashtable tblUpdatedValues = null;
    RadDropDownList ddlGenderCol = null;
 
    try
    {
        //Get the details of the item that needs to be updated
        tblUpdatedValues = new Hashtable();
 
        //Parse out the updated data
        UpdatedRow.OwnerTableView.ExtractValuesFromItem(tblUpdatedValues, UpdatedRow);
 
        ddlGenderCol = ((RadDropDownList)UpdatedRow.FindControl("ddlGender"));
 
        //Update the underlying data table with the updated information
        _propsSettings.Records.Rows[UpdatedRow.DataSetIndex]["FirstName"] = tblUpdatedValues["FirstName"].ToString();
        _propsSettings.Records.Rows[UpdatedRow.DataSetIndex]["MiddleName"] = tblUpdatedValues["MiddleName"].ToString();
        _propsSettings.Records.Rows[UpdatedRow.DataSetIndex]["LastName"] = tblUpdatedValues["LastName"].ToString();
 
        if (ddlGenderCol != null)
            _propsSettings.Records.Rows[UpdatedRow.DataSetIndex]["Gender"] = ddlGenderCol.SelectedValue;
        //_propsSettings.Records.Rows[UpdatedRow.DataSetIndex]["Gender"] = ((DropDownList)UpdatedRow.FindControl("ddlGender")).SelectedValue;
 
        _propsSettings.Records.Rows[UpdatedRow.DataSetIndex]["DoB"] = DateTime.Parse(tblUpdatedValues["DoB"].ToString()).ToString(@"M/d/yy");
        _propsSettings.Records.Rows[UpdatedRow.DataSetIndex]["ZipCode"] = tblUpdatedValues["ZipCode"].ToString();
        _propsSettings.Records.Rows[UpdatedRow.DataSetIndex]["Email"] = tblUpdatedValues["Email"].ToString();
        _propsSettings.Records.Rows[UpdatedRow.DataSetIndex]["RowCount"] = (UpdatedRow.DataSetIndex + 1);
 
        //Close out any open edit items and update the data displayed in the grid
        grdAthletes.MasterTableView.ClearEditItems();
        grdAthletes.Rebind();
 
        if (StartNewRow)
        {
            if ((_propsSettings.MaxTeamCount == 0) || (_propsSettings.Records.Rows.Count < _propsSettings.MaxTeamCount)) //Don't allow adding rows after the max
                CreateNewGridRow();
        }
    }
    catch (Exception ex)
    {
        System.Diagnostics.Debug.Print("Error: " + ex.ToString());
        Exceptions.ProcessModuleLoadException(this, ex);
    }
    finally
    {
        SaveControlState();
 
        //Clean up
        if (tblUpdatedValues != null)
        {
            tblUpdatedValues.Clear();
            tblUpdatedValues = null;
        }
 
        ddlGenderCol = null;
    }
}
 
protected void grdAthletes_EditCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
{
 
}
 
/// <summary>
/// Updates the RowCount field of the Athletes grid when users are added, deleted, or sorted.
/// </summary>
private void UpdateGridRowCounts()
{
    try
    {
        for (int iAthletes = 1; iAthletes <= _propsSettings.Records.Rows.Count; iAthletes++)
            _propsSettings.Records.Rows[iAthletes - 1]["RowCount"] = iAthletes;
    }
    catch (Exception ex)
    {
        System.Diagnostics.Debug.Print("Error: " + ex.ToString());
        Exceptions.ProcessModuleLoadException(this, ex);
    }
    finally
    {
        SaveControlState();
    }
}
 
/// <summary>
/// Creates a new row in the participants grid and puts it into Edit mode.
/// </summary>
private void CreateNewGridRow()
{
    try
    {
        UpdateGridRowCounts();
 
        //Close out any open edit items
        grdAthletes.MasterTableView.ClearEditItems();
 
        //Add the new row to the underlying data table
        AddNewRowInDataTable();
 
        //Select the new row and put it in edit mode
        grdAthletes.MasterTableView.Items[grdAthletes.MasterTableView.Items.Count - 1].Selected = true;
        grdAthletes.MasterTableView.Items[grdAthletes.MasterTableView.Items.Count - 1].Edit = true;
 
        //Update the grid to display the new row
        grdAthletes.Rebind();
    }
    catch (Exception ex)
    {
        System.Diagnostics.Debug.Print("Error: " + ex.ToString());
        Exceptions.ProcessModuleLoadException(this, ex);
    }
}
 
/// <summary>
/// Checks if the maximum number of athletes have been added and updates the UI to reflect it.
/// </summary>
/// <returns>A Boolean indicating if the maximum team size has been reached.</returns>
private bool CheckAtheleteTeamSize()
{
    bool ret_bReachedMax = false;
 
    try
    {
        if ((_propsSettings.MaxTeamCount == 0) || (_propsSettings.Records.Rows.Count < _propsSettings.MaxTeamCount)) //Don't allow adding rows after the max
            pnlMaxAthletesNote.Style["display"] = "none";
        else
        {
            ret_bReachedMax = true;
            lblMaxAthletes.Text = ("The maximum number of athletes for this team is " + _propsSettings.MaxTeamCount.ToString());
            pnlMaxAthletesNote.Style["display"] = "block";
        }
    }
    catch (Exception ex)
    {
        System.Diagnostics.Debug.Print("Error: " + ex.ToString());
        Exceptions.ProcessModuleLoadException(this, ex);
    }
 
    return ret_bReachedMax;
}
 
protected void grdAthletes_ItemCommand(object source, GridCommandEventArgs e)
{
    try
    {
        //Clear out any empty rows or bad data when a record has been canceled
        if (e.CommandName.Contains("Cancel"))
            CleanUpData();
        else if (e.CommandName.Contains("Delete"))
            UpdateGridRowCounts();
 
        switch (e.CommandName)
        {
            case "AddNewRow":
                if (!CheckAtheleteTeamSize()) //Don't allow adding rows after the max
                    CreateNewGridRow();
 
                break;
 
            default:
                break;
        }
    }
    catch (Exception ex)
    {
        System.Diagnostics.Debug.Print("Error: " + ex.ToString());
        Exceptions.ProcessModuleLoadException(this, ex);
    }
}
 
protected void grdAthletes_DeleteCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
{
    try
    {
        //Remove the row from the underlying data table
        _propsSettings.Records.Rows.RemoveAt(e.Item.DataSetIndex);
    }
    catch (Exception ex)
    {
        System.Diagnostics.Debug.Print("Error: " + ex.ToString());
        Exceptions.ProcessModuleLoadException(this, ex);
    }
    finally
    {
        SaveControlState();
    }
}
 
protected void grdAthletes_ItemDataBound(object sender, GridItemEventArgs e)
{
    Control ddlGenderSelector = null;
    Control ctrlFieldEditor = null;
    Control dtDoBEditor = null;
    Control ctrlFields = null;
 
    try
    {
        //Some controls don't load the values into the custom editor's automatically so force the values through
        if (e.Item.IsInEditMode)
        {
            ctrlFields = ((GridEditableItem)e.Item)["FirstName"].Controls[0];
            ((TextBox)ctrlFields).TabIndex = 50;
 
            ctrlFields = ((GridEditableItem)e.Item)["MiddleName"].Controls[0];
            ((TextBox)ctrlFields).TabIndex = 51;
 
            ctrlFields = ((GridEditableItem)e.Item)["LastName"].Controls[0];
            ((TextBox)ctrlFields).TabIndex = 52;
 
            ddlGenderSelector = e.Item.FindControl("ddlGender"); //Get the gender selection control
 
            //Load the current value for Gender into the column editor control
            if (ddlGenderSelector != null)
            {
                try
                {
                    ((RadDropDownList)ddlGenderSelector).SelectedValue = ((DataRowView)e.Item.DataItem)[3].ToString();
                    ((RadDropDownList)ddlGenderSelector).TabIndex = 53;
                }
                catch (Exception ex)
                { System.Diagnostics.Debug.Print("ERROR: " + ex.ToString()); }
            }
 
            //Set the min/max dates for athletes date of birth
            dtDoBEditor = ((GridEditableItem)e.Item)["DoB"].Controls[0];
 
            if (dtDoBEditor != null)
            {
                ((RadDatePicker)dtDoBEditor).TabIndex = 54;
 
                if (string.Compare(_propsSettings.ProgramCode, "Y", true) == 0)
                {
                    ((RadDatePicker)dtDoBEditor).SelectedDate = DateTime.Now.AddYears(-_propsSettings.MaxAge);
                    ((RadDatePicker)dtDoBEditor).MinDate = DateTime.Now.AddYears(-_propsSettings.MaxAge);
                }
                else
                {
                    ((RadDatePicker)dtDoBEditor).SelectedDate = DateTime.Now.AddYears(-_propsSettings.MinAge);
                    ((RadDatePicker)dtDoBEditor).MinDate = DateTime.MinValue;
                }
 
                if (_propsSettings.MinAge > 0)
                    ((RadDatePicker)dtDoBEditor).MaxDate = DateTime.Now.AddYears(-_propsSettings.MinAge);
                else
                    ((RadDatePicker)dtDoBEditor).MaxDate = DateTime.MaxValue;
 
                //Try to load the currently entered date, if it falls out of the available range, then select the minimum value
                try
                { ((RadDatePicker)dtDoBEditor).SelectedDate = DateTime.Parse(((DataRowView)e.Item.DataItem)[7].ToString()); }
                catch
                { ((RadDatePicker)dtDoBEditor).SelectedDate = ((RadDatePicker)dtDoBEditor).MinDate; }
            }
 
            ctrlFields = ((GridEditableItem)e.Item)["ZipCode"].Controls[0];
            ((RadMaskedTextBox)ctrlFields).TabIndex = 55;
            ((RadMaskedTextBox)ctrlFields).Width = 80;
 
            ctrlFields = ((GridEditableItem)e.Item)["Email"].Controls[0];
            ((TextBox)ctrlFields).TabIndex = 56;
            //((TextBox)ctrlFields).Attributes.Add("OnKeyPress", "return GridColKeyPress('" + ctrlFields.ClientID + "', event)");
            ((TextBox)ctrlFields).Attributes.Add("OnKeyDown", "return GridColKeyPress(this, event)");
 
            ctrlFields = ((GridEditableItem)e.Item)["DeleteColumn"].Controls[0];
            ((ImageButton)ctrlFields).TabIndex = -1;
 
            //Get the editor for the first field and set focus to it
            ctrlFieldEditor = ((GridEditableItem)e.Item)["FirstName"].Controls[0];
             
            if (ctrlFieldEditor != null)
                ctrlFieldEditor.Focus();
        }
    }
    catch (Exception ex)
    {
        System.Diagnostics.Debug.Print("Error: " + ex.ToString());
        Exceptions.ProcessModuleLoadException(this, ex);
    }
}
 
protected void grdAthletes_ItemCreated(object sender, GridItemEventArgs e)
{
    try
    {
        //Add the email validation handler
        if (e.Item is GridEditableItem && e.Item.IsInEditMode)
        {
            GridEditableItem item = e.Item as GridEditableItem;
            GridTextBoxColumnEditor editor = (GridTextBoxColumnEditor)item.EditManager.GetColumnEditor("Email");
            TableCell cell = (TableCell)editor.TextBoxControl.Parent;
            RegularExpressionValidator val = new RegularExpressionValidator();
 
            val.ControlToValidate = editor.TextBoxControl.ID;
            val.ValidationExpression = (@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
            val.ErrorMessage = "Invalid email address!";
            val.CssClass = "red";
            cell.Controls.Add(val);
        }
    }
    catch (Exception ex)
    {
        System.Diagnostics.Debug.Print("Error: " + ex.ToString());
        Exceptions.ProcessModuleLoadException(this, ex);
    }
}
 
/// <summary>
/// Adds a new row to the Athletes grid.
/// </summary>
private void AddNewRowInDataTable()
{
    DataRow drNewAthlete = null;
 
    try
    {
        drNewAthlete = _propsSettings.Records.NewRow();
 
        //Populate the default field values
        drNewAthlete["FirstName"] = string.Empty;
        drNewAthlete["MiddleName"] = string.Empty;
        drNewAthlete["LastName"] = string.Empty;
 
        if (string.Compare(_propsSettings.DefaultGender, "F", true) == 0)
            drNewAthlete["Gender"] = "Female";
        else
            drNewAthlete["Gender"] = "Male";
 
        if (string.Compare(_propsSettings.ProgramCode, "Y", true) == 0)
            drNewAthlete["DoB"] = DateTime.Now.AddYears(-_propsSettings.MaxAge);
        else
            drNewAthlete["DoB"] = DateTime.MinValue;
 
        drNewAthlete["Email"] = string.Empty;
        drNewAthlete["ZipCode"] = string.Empty;
        drNewAthlete["UniqueID"] = string.Empty;
        drNewAthlete["RowCount"] = (_propsSettings.Records.Rows.Count + 1);
 
        //Add the new row to the grid
        _propsSettings.Records.Rows.Add(drNewAthlete);
        grdAthletes.Rebind();
 
    }
    catch (Exception ex)
    {
        System.Diagnostics.Debug.Print("Error: " + ex.ToString());
        Exceptions.ProcessModuleLoadException(this, ex);
    }
    finally
    {
        SaveControlState();
    }
}
 
/// <summary>
/// Cleans up the Athletes grid data to make sure any invalid rows are removed.
/// </summary>
private void CleanUpData()
{
    try
    {
        if (_propsSettings.Records.Rows.Count > 0)
        {
            //Start at the end so that removing rows won't cause the index to be incorrect
            for (int iAthletes = (_propsSettings.Records.Rows.Count - 1); iAthletes > -1; iAthletes--)
            {
                try
                {
                    //Make sure all of the fields have valid data
                    if (string.IsNullOrEmpty(_propsSettings.Records.Rows[iAthletes][0].ToString()) || string.IsNullOrEmpty(_propsSettings.Records.Rows[iAthletes][2].ToString()) ||
                        string.IsNullOrEmpty(_propsSettings.Records.Rows[iAthletes][3].ToString()) || string.IsNullOrEmpty(_propsSettings.Records.Rows[iAthletes][4].ToString()))
                        _propsSettings.Records.Rows.RemoveAt(iAthletes); //Invalid data found, remove the row
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.Print("Error: " + ex.ToString());
                }
            }
        }
    }
    catch (Exception ex)
    {
        System.Diagnostics.Debug.Print("Error: " + ex.ToString());
        Exceptions.ProcessModuleLoadException(this, ex);
    }
    finally
    {
        SaveControlState();
    }
}
 
#endregion

So ... as it stands, something has broken my Enter and Esc key handling.  They keys get trapped but for some reason aren't firing the grid events like they used to (they were working until recently when I started trying to add the Tab functionality).  Enter would commit the row and trigger a new row to be created in edit mode, Escape cancelled the current row insert/update, and I wanted to add Tab in the last field acting like the Enter key was pressed.  But right now, none are able to cause the grid to fire off the events to make those things happen.
0
J
Top achievements
Rank 1
answered on 22 Apr 2013, 02:47 PM
By making the following changes I was able to get my Enter and Esc keys processed again.  Still no luck with getting Tab to work the way I want though.

Any ideas?  Anyone?

<telerik:RadCodeBlock ID="codScriptManager" runat="server">
    <script type="text/javascript" language="javascript">
        var bHasChanges = false;
        var colUIInputItems = null;
        var colDropdownLists = null;
        var rowEditedItem = null;
        var sAthleteGridID = "<%=grdAthletes.ClientID %>";
 
        function btnFindMember_ClientClick(sender) {
            var btnFind = document.getElementById("<%=btnFindMember.ClientID %>");
 
            if (btnFind != null) {
                btnFind.disabled = true;
                btnFind.className = "btn-clear-member";
                btnFind.value = "Searching...";
            }
 
            return true;
        }
 
        /// <summary>
        /// Checks if the currently focused item is inside the grid.
        /// </summary>
        function IsItemInsideGrid() {
            var ret_bIsInGrid = false;
            var objCurItem = document.activeElement;
            var sObjectChain = "";
 
            if (objCurItem != null) {
                sObjectChain = objCurItem.id;
 
                //Keep looking at the object's parent object until the grid or top-most parent is found
                while (objCurItem.parentNode) {
                    objCurItem = objCurItem.parentNode;
 
                    if ((objCurItem != null) && (objCurItem.id.length > 0)) {
                        sObjectChain += (" -> " + objCurItem.id);
 
                        if (objCurItem.id.indexOf(sAthleteGridID) > -1) {
                            ret_bIsInGrid = true;
                            break;
                        }
                    }
                }
            }
 
            if (!ret_bIsInGrid) {
                //If currently editing a row, commit the changes and stop the editing
                if (rowEditedItem) {
                    bHasChanges = false;
                    $find(sAthleteGridID).get_masterTableView().updateItem(rowEditedItem);
 
 
                    $find(sAthleteGridID).get_masterTableView().fireCommand("CancelAll", ""); //Cancel any editing activities in the grid
                    $find(sAthleteGridID).get_masterTableView().clearSelectedItems(); //De-select any rows
                }
            }
 
            return ret_bIsInGrid;
        }
 
        /// <summary>
        /// Handles the client side events when the athletes grid loses focus.
        /// </summary>
        function grdAthletes_LostFocus(sender, eventArgs) {
            setTimeout(IsItemInsideGrid, 50);
        }
 
        /// <summary>
        /// Handles the client side RowClick event of the Athletes grid.
        /// </summary>
        function RowClick(sender, eventArgs) {
            //
        }
 
        /// <summary>
        /// Handles the client side RowDblClick event of the Athletes grid.
        /// </summary>
        function RowDblClick(sender, eventArgs) {
            rowEditedItem = eventArgs.get_itemIndexHierarchical();
            $find(sAthleteGridID).get_masterTableView().editItem(rowEditedItem);
        }
 
        /// <summary>
        /// Handles the client side GridCommand event of the Athletes grid.
        /// </summary>
        function GridCommand(sender, args) {
            if (args.get_commandName() != "Edit") {
                rowEditedItem = null;
            }
        }
 
        /// <summary>
        /// Handles the client side GridCreated event of the Athletes grid.
        /// </summary>
        function GridCreated(sender, eventArgs) {
            var objGrid = sender.get_element();
            var arrUIObjects = [];
            var lowerType = null;
 
            colUIInputItems = objGrid.getElementsByTagName("input");
 
            //Set up change tracking for the input controls in the grid
            for (var iInputItems = 0; iInputItems < colUIInputItems.length; iInputItems++) {
                lowerType = colUIInputItems[iInputItems].type.toLowerCase();
 
                if ((lowerType == "hidden") || (lowerType == "button"))
                    continue;
 
                if ((colUIInputItems[iInputItems].id.indexOf("PageSizeComboBox") == -1) && (colUIInputItems[iInputItems].type.toLowerCase() != "checkbox"))
                    Array.add(arrUIObjects, colUIInputItems[iInputItems]);
 
                colUIInputItems[iInputItems].onchange = TrackChanges;
            }
 
            colDropdownLists = objGrid.getElementsByTagName("select");
 
            //Set up change tracking for the drop down controls in the grid
            for (var iDropDowns = 0; iDropDowns < colDropdownLists.length; iDropDowns++)
                colDropdownLists[iDropDowns].onchange = TrackChanges;
 
            setTimeout(function () { if (arrUIObjects[0]) arrUIObjects[0].focus(); }, 100);
        }
 
        /// <summary>
        /// Handles the client side RowSelected event of the Athletes grid.
        /// </summary>
        function RowSelected(sender, eventArgs) {
            //If editing a row and changes are pending, commit the changes and stop the editing
            if (bHasChanges && rowEditedItem) {
                bHasChanges = false;
                $find(sAthleteGridID).get_masterTableView().updateItem(rowEditedItem);
            }
        }
 
        /// <summary>
        /// Handles the client side Change event for controls in the Athletes grid.
        /// </summary>
        function TrackChanges(e) {
            bHasChanges = true;
        }
 
        /// <summary>
        /// Handles the client side KeyPress event of the Athletes grid.
        /// </summary>
        function OnKeyPress(sender, args) {
            //Check for the Enter key being pressed
            if ((args._domEvent.charCode == 13) || (args.get_keyCode() == 13)) {
                //If currently editing a row, commit the changes and stop the editing
                if (rowEditedItem) {
                    bHasChanges = false;
                    $find(sAthleteGridID).get_masterTableView().updateItem(rowEditedItem);
                }
            }
            else if ((args.get_keyCode() == 27) || (args._domEvent.charCode == 27)) //Check for the Esc key being press
            {
                $find(sAthleteGridID).get_masterTableView().fireCommand("CancelAll", ""); //Cancel any editing activities in the grid
                $find(sAthleteGridID).get_masterTableView().clearSelectedItems(); //De-select any rows
            }
        }
    </script>
</telerik:RadCodeBlock>

<telerik:RadGrid ID="grdAthletes" runat="server" AllowAutomaticDeletes="True" AllowSorting="True"
                        PageSize="12" AutoGenerateColumns="False" OnNeedDataSource="grdAthletes_NeedDataSource"
                        OnItemCommand="grdAthletes_ItemCommand" OnPreRender="grdAthletes_PreRender" OnUpdateCommand="grdAthletes_UpdateCommand"
                        Width="100%" OnDeleteCommand="grdAthletes_DeleteCommand" OnEditCommand="grdAthletes_EditCommand"
                        OnItemDataBound="grdAthletes_ItemDataBound" ShowStatusBar="True" AllowAutomaticInserts="True"
                        AllowAutomaticUpdates="True" OnItemCreated="grdAthletes_ItemCreated" Skin="Metro"
                        BorderStyle="None" CellSpacing="0" GridLines="None" ForeColor="White" BackColor="Transparent"
                        ShowFooter="True" TabIndex="17" causesvalidation="false">
                        <ValidationSettings ValidationGroup="AthletesGrid" />
                        <ClientSettings AllowKeyboardNavigation="True">
                            <Selecting AllowRowSelect="True" />
                            <KeyboardNavigationSettings AllowSubmitOnEnter="True" AllowActiveRowCycle="True" />
                            <Scrolling AllowScroll="True" UseStaticHeaders="True" SaveScrollPosition="true" />
                            <ClientEvents OnKeyPress="OnKeyPress" OnRowSelected="RowSelected" OnRowClick="RowClick"
                                OnRowDblClick="RowDblClick" OnGridCreated="GridCreated" OnCommand="GridCommand" />
                            <Resizing ShowRowIndicatorColumn="False" />
                        </ClientSettings>
                        <AlternatingItemStyle BackColor="LightGray" BorderStyle="None" ForeColor="Black" />
                        <MasterTableView NoMasterRecordsText="No athletes to display." EditMode="InPlace"
                            CommandItemDisplay="Bottom" BorderStyle="None" BackColor="Transparent" ShowFooter="False">
                            <HeaderStyle BorderStyle="None" Font-Bold="True" Font-Size="Medium" ForeColor="White"
                                Height="48px" HorizontalAlign="Left" VerticalAlign="Middle" Wrap="True" />
                            <CommandItemStyle CssClass="rgCommandRow" />
                            <FooterStyle BorderStyle="None" CssClass="grid-footer" />
                            <CommandItemTemplate>
                                <div>
                                    <asp:LinkButton ID="btnAddNew" runat="server" CommandName="AddNewRow" TabIndex="18" CausesValidation="false">
                                        <asp:Image ID="Image1" runat="server" ImageUrl="~/Images/112_Plus_Green_32x42_72.png" CssClass="GridCommandBarItemImage" AlternateText="Add Athlete" /> Add Athlete</asp:LinkButton>  
                                </div>
                            </CommandItemTemplate>
                            <CommandItemSettings ExportToPdfText="Export to PDF" ShowRefreshButton="False" AddNewRecordText="Add Athlete">
                            </CommandItemSettings>
                            <RowIndicatorColumn FilterControlAltText="Filter RowIndicator column">
                                <HeaderStyle Width="20px"></HeaderStyle>
                            </RowIndicatorColumn>
                            <ExpandCollapseColumn FilterControlAltText="Filter ExpandColumn column">
                                <HeaderStyle Width="20px"></HeaderStyle>
                            </ExpandCollapseColumn>
                            <EditFormSettings EditFormType="Template">
                                <EditColumn FilterControlAltText="Filter EditCommandColumn column" CancelImageUrl="Cancel.gif"
                                    InsertImageUrl="Update.gif" UpdateImageUrl="Update.gif" Visible="true" Display="true">
                                </EditColumn>
                            </EditFormSettings>
                            <ItemStyle BackColor="White" BorderStyle="None" ForeColor="Black" />
                            <AlternatingItemStyle BackColor="LightGray" BorderStyle="None" ForeColor="Black" />
                            <EditItemStyle BackColor="Gainsboro" BorderStyle="None" />
                            <PagerStyle PageSizeControlType="RadComboBox"></PagerStyle>
                            <Columns>
                                <telerik:GridBoundColumn ConvertEmptyStringToNull="False" DataField="RowCount" EmptyDataText="" FilterControlAltText="Filter RowCount column" HeaderText="" SortExpression="RowCount" UniqueName="RowCount" ReadOnly="true">
                                    <HeaderStyle Wrap="False" HorizontalAlign="Left" Width="24px" CssClass="grid-header grid-header-first" />
                                    <ItemStyle HorizontalAlign="Left" VerticalAlign="Middle" Width="24px" />
                                </telerik:GridBoundColumn>
                                <telerik:GridBoundColumn DataField="FirstName" HeaderText="Name<br />First"
                                    UniqueName="FirstName" ConvertEmptyStringToNull="False" SortExpression="FirstName"
                                    EmptyDataText="" ColumnEditorID="txtGridEdit_FirstName" ColumnGroupName="AthleteName"
                                    ShowSortIcon="False">
                                    <ColumnValidationSettings EnableRequiredFieldValidation="True">
                                        <RequiredFieldValidator ForeColor="Red" ErrorMessage="* Required" Display="Dynamic" Font-Bold="True" SetFocusOnError="True" ValidationGroup="AthletesGrid" /></ColumnValidationSettings>
                                    <HeaderStyle Wrap="False" HorizontalAlign="Left" Width="70px" CssClass="grid-header" VerticalAlign="Middle"/>
                                    <ItemStyle HorizontalAlign="Left" Width="100%" VerticalAlign="Top" />
                                </telerik:GridBoundColumn>
                                <telerik:GridBoundColumn DataField="MiddleName" HeaderText="<br/>M" UniqueName="MiddleName"
                                    ConvertEmptyStringToNull="False" EmptyDataText="" SortExpression="MiddleName"
                                    ColumnEditorID="txtGridEdit_MiddleName" ColumnGroupName="AthleteName" ShowSortIcon="False">
                                    <HeaderStyle Wrap="False" HorizontalAlign="Left" Width="50px" CssClass="grid-header" VerticalAlign="Middle"/>
                                    <ItemStyle HorizontalAlign="Left" Width="100%" VerticalAlign="Top" />
                                </telerik:GridBoundColumn>
                                <telerik:GridBoundColumn DataField="LastName" HeaderText="<br/>Last" UniqueName="LastName"
                                    ConvertEmptyStringToNull="False" SortExpression="LastName" EmptyDataText="" ColumnEditorID="txtGridEdit_LastName"
                                    ColumnGroupName="AthleteName" ShowSortIcon="False">
                                    <ColumnValidationSettings EnableRequiredFieldValidation="True">
                                        <RequiredFieldValidator ForeColor="Red" ErrorMessage="* Required" Display="Dynamic" Font-Bold="True" SetFocusOnError="True" ValidationGroup="AthletesGrid" /></ColumnValidationSettings>
                                    <HeaderStyle Wrap="False" HorizontalAlign="Left" Width="70px" CssClass="grid-header" VerticalAlign="Middle"/>
                                    <ItemStyle HorizontalAlign="Left" Width="100%" VerticalAlign="Top" />
                                </telerik:GridBoundColumn>
                                <telerik:GridTemplateColumn HeaderText="Gender" SortExpression="Gender" UniqueName="Gender"
                                    DataField="Gender" FilterControlAltText="Filter Gender column"
                                    ShowSortIcon="False">
                                    <ItemTemplate>
                                        <%# DataBinder.Eval(Container.DataItem, "Gender") %></ItemTemplate>
                                    <EditItemTemplate>
                                        <telerik:RadDropDownList ID="ddlGender" runat="server" Width="100%" TabIndex="19">
                                            <Items>
                                                <telerik:DropDownListItem Text="Female" Value="Female" />
                                                <telerik:DropDownListItem Text="Male" Value="Male" Selected="true" />
                                            </Items>
                                        </telerik:RadDropDownList>
                                    </EditItemTemplate>
                                    <HeaderStyle Wrap="False" HorizontalAlign="Left" Width="85px" CssClass="grid-header" VerticalAlign="Top" />
                                    <ItemStyle HorizontalAlign="Left" Width="90%" VerticalAlign="Top" />
                                </telerik:GridTemplateColumn>
                                <telerik:GridDateTimeColumn ConvertEmptyStringToNull="False" DataField="DoB" FilterControlAltText="Filter DoB column"
                                    HeaderText="Date of Birth" SortExpression="DoB" UniqueName="DoB" DataFormatString="{0:M/d/yy}"
                                    DataType="System.DateTime" EmptyDataText="" ColumnEditorID="dtGridEdit_DoB" ShowFilterIcon="False"
                                    EditDataFormatString="M/d/yy" MaxLength="8" ShowSortIcon="False">
                                    <ColumnValidationSettings EnableRequiredFieldValidation="True">
                                        <RequiredFieldValidator ForeColor="Red" ErrorMessage="* Max Age Exceeded" Display="Dynamic" Font-Bold="True" SetFocusOnError="True" ValidationGroup="AthletesGrid" />
                                    </ColumnValidationSettings>
                                    <HeaderStyle Wrap="False" HorizontalAlign="Left" Width="106px" CssClass="grid-header" VerticalAlign="Top" />
                                    <ItemStyle Width="100%" HorizontalAlign="Left" VerticalAlign="Top"></ItemStyle>
                                </telerik:GridDateTimeColumn>
                                <telerik:GridMaskedColumn ConvertEmptyStringToNull="False" DataField="ZipCode" DataFormatString="{0:#####}"
                                    FilterControlAltText="Filter ZipCode column" HeaderText="Zip Code" Mask="#####"
                                    SortExpression="ZipCode" UniqueName="ZipCode" EmptyDataText="" ShowSortIcon="False">
                                    <ColumnValidationSettings EnableRequiredFieldValidation="True">
                                        <RequiredFieldValidator ForeColor="Red" ErrorMessage=" * Required" Display="Dynamic" Font-Bold="True" SetFocusOnError="True" ValidationGroup="AthletesGrid" /></ColumnValidationSettings>
                                    <HeaderStyle Wrap="False" HorizontalAlign="Left" Width="80px" CssClass="grid-header" VerticalAlign="Top" />
                                    <ItemStyle Width="100%" HorizontalAlign="Left" VerticalAlign="Top"></ItemStyle>
                                </telerik:GridMaskedColumn>
                                <telerik:GridBoundColumn ConvertEmptyStringToNull="False" DataField="Email" FilterControlAltText="Filter Email column"
                                    HeaderText="Email" SortExpression="Email" UniqueName="Email" EmptyDataText=""
                                    ColumnEditorID="txtGridEdit_General_Large" ShowSortIcon="False">
                                    <HeaderStyle Width="100px" Wrap="False" HorizontalAlign="Left" CssClass="grid-header" VerticalAlign="Top"/>
                                    <ItemStyle HorizontalAlign="Left" Width="100%" VerticalAlign="Top" />
                                </telerik:GridBoundColumn>
                                <telerik:GridBoundColumn ConvertEmptyStringToNull="False" DataField="UniqueID" EmptyDataText=""
                                    FilterControlAltText="Filter column column" HeaderText="Unique ID" SortExpression="UniqueID"
                                    UniqueName="UniqueID" Visible="False">
                                    <HeaderStyle CssClass="grid-header" />
                                    <ItemStyle HorizontalAlign="Left" VerticalAlign="Top" />
                                </telerik:GridBoundColumn>
                                <telerik:GridButtonColumn ButtonType="ImageButton" CommandName="Edit" FilterControlAltText="Filter EditColumn column"
                                    ImageUrl="Images/126_Edit_16x16_72.png" Text="" UniqueName="EditColumn" Resizable="false"
                                    ConfirmDialogType="RadWindow">
                                    <HeaderStyle Wrap="False" HorizontalAlign="Left" Width="24px" CssClass="grid-header">
                                    </HeaderStyle>
                                    <ItemStyle Width="100%" HorizontalAlign="Right" VerticalAlign="Top" />
                                </telerik:GridButtonColumn>
                                <telerik:GridButtonColumn ButtonType="ImageButton" CommandName="Delete" FilterControlAltText="Filter DeleteColumn column"
                                    ImageUrl="Images/305_Close_16x16_72.png" Text="" UniqueName="DeleteColumn" Resizable="false"
                                    ConfirmText="Remove this athelete?" ConfirmDialogType="RadWindow" ConfirmTitle="Remove"
                                    ShowInEditForm="True">
                                    <HeaderStyle Wrap="False" HorizontalAlign="Left" Width="24px" CssClass="grid-header grid-header-last">
                                    </HeaderStyle>
                                    <ItemStyle Width="100%" HorizontalAlign="Right" VerticalAlign="Top" />
                                </telerik:GridButtonColumn>
                            </Columns>
                        </MasterTableView><EditItemStyle BackColor="Gainsboro" BorderStyle="None" />
                        <FooterStyle BorderStyle="None" />
                        <HeaderStyle BorderStyle="None" Height="48px" HorizontalAlign="Left" VerticalAlign="Middle" />
                        <CommandItemStyle CssClass="rgCommandRow" />
                        <ItemStyle BackColor="White" BorderStyle="None" ForeColor="Black" />
                        <PagerStyle PageSizeControlType="RadComboBox"></PagerStyle>
                        <SelectedItemStyle BorderStyle="None" />
                        <FilterMenu EnableImageSprites="False">
                        </FilterMenu>
                        <HeaderContextMenu CssClass="GridContextMenu GridContextMenu_Default">
                        </HeaderContextMenu>
                    </telerik:RadGrid>
                    <telerik:GridTextBoxColumnEditor ID="txtGridEdit_FirstName" runat="server" TextBoxStyle-Width="99%" />
                    <telerik:GridTextBoxColumnEditor ID="txtGridEdit_MiddleName" runat="server" TextBoxStyle-Width="99%" />
                    <telerik:GridTextBoxColumnEditor ID="txtGridEdit_LastName" runat="server" TextBoxStyle-Width="99%" />
                    <telerik:GridDropDownListColumnEditor ID="cmbGridEdit_Gender" runat="server" DropDownStyle-Width="100px" />
                    <telerik:GridDateTimeColumnEditor runat="server" ID="dtGridEdit_DoB" TextBoxStyle-Width="99%"  />
                    <telerik:GridTextBoxColumnEditor ID="txtGridEdit_Email" runat="server" TextBoxStyle-Width="99%"  />
0
Angel Petrov
Telerik team
answered on 23 Apr 2013, 01:06 PM
Hi Juan,

The problem in your case is that the tab click is being escaped thus the OnKeyPress event will not fire. To resolve the problem I suggest that you modify your last column to be a GridTemplateColumn and wrap the input control in the EditItemTemplate in a div. Later you can intercept the OnKeyDown event of the div and execute the logic desired:

ASPX:
<telerik:GridTemplateColumn UniqueName="TemplateColumn">
                    <ItemTemplate>
                        Your template
                    </ItemTemplate>
                    <EditItemTemplate>
                        <div id="somediv" onkeydown="keyDownEvent(this)">
                            //your input control
                        </div>
                    </EditItemTemplate>
                </telerik:GridTemplateColumn>

JavaScript:
function keyDownEvent(e)
    {
        //Put the JavaScript logic here.
    }

Regards,
Angel Petrov
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
J
Top achievements
Rank 1
answered on 23 Apr 2013, 01:39 PM
No, that's not it, but thanks.  I've got it fixed and working now for Enter, Escape, and Tab and events are now being triggered by the 'fireCommand' calls.  I still need to clean up the code now and remove some things that are no longer needed and what not but here's where it is right now.

Updated HTML:
<telerik:RadGrid ID="grdAthletes" runat="server" AllowAutomaticDeletes="True" AllowSorting="True"
                        PageSize="12" AutoGenerateColumns="False" OnNeedDataSource="grdAthletes_NeedDataSource"
                        OnItemCommand="grdAthletes_ItemCommand" OnPreRender="grdAthletes_PreRender" OnUpdateCommand="grdAthletes_UpdateCommand"
                        Width="100%" OnDeleteCommand="grdAthletes_DeleteCommand" OnEditCommand="grdAthletes_EditCommand"
                        OnItemDataBound="grdAthletes_ItemDataBound" ShowStatusBar="True" AllowAutomaticInserts="True"
                        AllowAutomaticUpdates="True" OnItemCreated="grdAthletes_ItemCreated" Skin="Metro"
                        BorderStyle="None" CellSpacing="0" GridLines="None" ForeColor="White" BackColor="Transparent"
                        ShowFooter="True" TabIndex="17" causesvalidation="false">
                        <ValidationSettings ValidationGroup="AthletesGrid" />
                        <ClientSettings AllowKeyboardNavigation="True">
                            <Selecting AllowRowSelect="True" />
                            <KeyboardNavigationSettings AllowSubmitOnEnter="True" AllowActiveRowCycle="True" />
                            <Scrolling AllowScroll="True" UseStaticHeaders="True" SaveScrollPosition="true" />
                            <ClientEvents OnKeyPress="OnKeyPress" OnRowSelected="RowSelected" OnRowClick="RowClick"
                                OnRowDblClick="RowDblClick" OnGridCreated="GridCreated" OnCommand="GridCommand" />
                            <Resizing ShowRowIndicatorColumn="False" />
                        </ClientSettings>
                        <AlternatingItemStyle BackColor="LightGray" BorderStyle="None" ForeColor="Black" />
                        <MasterTableView NoMasterRecordsText="No athletes to display." EditMode="InPlace"
                            CommandItemDisplay="Bottom" BorderStyle="None" BackColor="Transparent" ShowFooter="False">
                            <HeaderStyle BorderStyle="None" Font-Bold="True" Font-Size="Medium" ForeColor="White"
                                Height="48px" HorizontalAlign="Left" VerticalAlign="Middle" Wrap="True" />
                            <CommandItemStyle CssClass="rgCommandRow" />
                            <FooterStyle BorderStyle="None" CssClass="grid-footer" />
                            <CommandItemTemplate>
                                <div>
                                    <asp:LinkButton ID="btnAddNew" runat="server" CommandName="AddNewRow" TabIndex="18" CausesValidation="false">
                                        <asp:Image ID="Image1" runat="server" ImageUrl="~/Images/112_Plus_Green_32x42_72.png" CssClass="GridCommandBarItemImage" AlternateText="Add Athlete" /> Add Athlete</asp:LinkButton>  
                                </div>
                            </CommandItemTemplate>
                            <CommandItemSettings ExportToPdfText="Export to PDF" ShowRefreshButton="False" AddNewRecordText="Add Athlete">
                            </CommandItemSettings>
                            <RowIndicatorColumn FilterControlAltText="Filter RowIndicator column">
                                <HeaderStyle Width="20px"></HeaderStyle>
                            </RowIndicatorColumn>
                            <ExpandCollapseColumn FilterControlAltText="Filter ExpandColumn column">
                                <HeaderStyle Width="20px"></HeaderStyle>
                            </ExpandCollapseColumn>
                            <EditFormSettings EditFormType="Template">
                                <EditColumn FilterControlAltText="Filter EditCommandColumn column" CancelImageUrl="Cancel.gif"
                                    InsertImageUrl="Update.gif" UpdateImageUrl="Update.gif" Visible="true" Display="true">
                                </EditColumn>
                            </EditFormSettings>
                            <ItemStyle BackColor="White" BorderStyle="None" ForeColor="Black" />
                            <AlternatingItemStyle BackColor="LightGray" BorderStyle="None" ForeColor="Black" />
                            <EditItemStyle BackColor="Gainsboro" BorderStyle="None" />
                            <PagerStyle PageSizeControlType="RadComboBox"></PagerStyle>
                            <Columns>
                                <telerik:GridBoundColumn ConvertEmptyStringToNull="False" DataField="RowCount" EmptyDataText="" FilterControlAltText="Filter RowCount column" HeaderText="" SortExpression="RowCount" UniqueName="RowCount" ReadOnly="true">
                                    <HeaderStyle Wrap="False" HorizontalAlign="Left" Width="24px" CssClass="grid-header grid-header-first" />
                                    <ItemStyle HorizontalAlign="Left" VerticalAlign="Middle" Width="24px" />
                                </telerik:GridBoundColumn>
                                <telerik:GridBoundColumn DataField="FirstName" HeaderText="Name<br />First"
                                    UniqueName="FirstName" ConvertEmptyStringToNull="False" SortExpression="FirstName"
                                    EmptyDataText="" ColumnEditorID="txtGridEdit_FirstName" ColumnGroupName="AthleteName"
                                    ShowSortIcon="False">
                                    <ColumnValidationSettings EnableRequiredFieldValidation="True">
                                        <RequiredFieldValidator ForeColor="Red" ErrorMessage="* Required" Display="Dynamic" Font-Bold="True" SetFocusOnError="True" ValidationGroup="AthletesGrid" /></ColumnValidationSettings>
                                    <HeaderStyle Wrap="False" HorizontalAlign="Left" Width="70px" CssClass="grid-header" VerticalAlign="Middle"/>
                                    <ItemStyle HorizontalAlign="Left" Width="100%" VerticalAlign="Top" />
                                </telerik:GridBoundColumn>
                                <telerik:GridBoundColumn DataField="MiddleName" HeaderText="<br/>M" UniqueName="MiddleName"
                                    ConvertEmptyStringToNull="False" EmptyDataText="" SortExpression="MiddleName"
                                    ColumnEditorID="txtGridEdit_MiddleName" ColumnGroupName="AthleteName" ShowSortIcon="False">
                                    <HeaderStyle Wrap="False" HorizontalAlign="Left" Width="50px" CssClass="grid-header" VerticalAlign="Middle"/>
                                    <ItemStyle HorizontalAlign="Left" Width="100%" VerticalAlign="Top" />
                                </telerik:GridBoundColumn>
                                <telerik:GridBoundColumn DataField="LastName" HeaderText="<br/>Last" UniqueName="LastName"
                                    ConvertEmptyStringToNull="False" SortExpression="LastName" EmptyDataText="" ColumnEditorID="txtGridEdit_LastName"
                                    ColumnGroupName="AthleteName" ShowSortIcon="False">
                                    <ColumnValidationSettings EnableRequiredFieldValidation="True">
                                        <RequiredFieldValidator ForeColor="Red" ErrorMessage="* Required" Display="Dynamic" Font-Bold="True" SetFocusOnError="True" ValidationGroup="AthletesGrid" /></ColumnValidationSettings>
                                    <HeaderStyle Wrap="False" HorizontalAlign="Left" Width="70px" CssClass="grid-header" VerticalAlign="Middle"/>
                                    <ItemStyle HorizontalAlign="Left" Width="100%" VerticalAlign="Top" />
                                </telerik:GridBoundColumn>
                                <telerik:GridTemplateColumn HeaderText="Gender" SortExpression="Gender" UniqueName="Gender"
                                    DataField="Gender" FilterControlAltText="Filter Gender column"
                                    ShowSortIcon="False">
                                    <ItemTemplate>
                                        <%# DataBinder.Eval(Container.DataItem, "Gender") %></ItemTemplate>
                                    <EditItemTemplate>
                                        <telerik:RadDropDownList ID="ddlGender" runat="server" Width="100%" TabIndex="19">
                                            <Items>
                                                <telerik:DropDownListItem Text="Female" Value="Female" />
                                                <telerik:DropDownListItem Text="Male" Value="Male" Selected="true" />
                                            </Items>
                                        </telerik:RadDropDownList>
                                    </EditItemTemplate>
                                    <HeaderStyle Wrap="False" HorizontalAlign="Left" Width="85px" CssClass="grid-header" VerticalAlign="Top" />
                                    <ItemStyle HorizontalAlign="Left" Width="90%" VerticalAlign="Top" />
                                </telerik:GridTemplateColumn>
                                <telerik:GridDateTimeColumn ConvertEmptyStringToNull="False" DataField="DoB" FilterControlAltText="Filter DoB column"
                                    HeaderText="Date of Birth" SortExpression="DoB" UniqueName="DoB" DataFormatString="{0:M/d/yy}"
                                    DataType="System.DateTime" EmptyDataText="" ColumnEditorID="dtGridEdit_DoB" ShowFilterIcon="False"
                                    EditDataFormatString="M/d/yy" MaxLength="8" ShowSortIcon="False">
                                    <ColumnValidationSettings EnableRequiredFieldValidation="True">
                                        <RequiredFieldValidator ForeColor="Red" ErrorMessage="* Max Age Exceeded" Display="Dynamic" Font-Bold="True" SetFocusOnError="True" ValidationGroup="AthletesGrid" />
                                    </ColumnValidationSettings>
                                    <HeaderStyle Wrap="False" HorizontalAlign="Left" Width="106px" CssClass="grid-header" VerticalAlign="Top" />
                                    <ItemStyle Width="100%" HorizontalAlign="Left" VerticalAlign="Top"></ItemStyle>
                                </telerik:GridDateTimeColumn>
                                <telerik:GridMaskedColumn ConvertEmptyStringToNull="False" DataField="ZipCode" DataFormatString="{0:#####}"
                                    FilterControlAltText="Filter ZipCode column" HeaderText="Zip Code" Mask="#####"
                                    SortExpression="ZipCode" UniqueName="ZipCode" EmptyDataText="" ShowSortIcon="False">
                                    <ColumnValidationSettings EnableRequiredFieldValidation="True">
                                        <RequiredFieldValidator ForeColor="Red" ErrorMessage=" * Required" Display="Dynamic" Font-Bold="True" SetFocusOnError="True" ValidationGroup="AthletesGrid" /></ColumnValidationSettings>
                                    <HeaderStyle Wrap="False" HorizontalAlign="Left" Width="80px" CssClass="grid-header" VerticalAlign="Top" />
                                    <ItemStyle Width="100%" HorizontalAlign="Left" VerticalAlign="Top"></ItemStyle>
                                </telerik:GridMaskedColumn>
                                <telerik:GridBoundColumn ConvertEmptyStringToNull="False" DataField="Email" FilterControlAltText="Filter Email column"
                                    HeaderText="Email" SortExpression="Email" UniqueName="Email" EmptyDataText=""
                                    ColumnEditorID="txtGridEdit_General_Large" ShowSortIcon="False">
                                    <HeaderStyle Width="100px" Wrap="False" HorizontalAlign="Left" CssClass="grid-header" VerticalAlign="Top"/>
                                    <ItemStyle HorizontalAlign="Left" Width="100%" VerticalAlign="Top" />
                                </telerik:GridBoundColumn>
                                <telerik:GridBoundColumn ConvertEmptyStringToNull="False" DataField="UniqueID" EmptyDataText=""
                                    FilterControlAltText="Filter column column" HeaderText="Unique ID" SortExpression="UniqueID"
                                    UniqueName="UniqueID" Visible="False">
                                    <HeaderStyle CssClass="grid-header" />
                                    <ItemStyle HorizontalAlign="Left" VerticalAlign="Top" />
                                </telerik:GridBoundColumn>
                                <telerik:GridButtonColumn ButtonType="ImageButton" CommandName="Edit" FilterControlAltText="Filter EditColumn column"
                                    ImageUrl="Images/126_Edit_16x16_72.png" Text="" UniqueName="EditColumn" Resizable="false"
                                    ConfirmDialogType="RadWindow">
                                    <HeaderStyle Wrap="False" HorizontalAlign="Left" Width="24px" CssClass="grid-header">
                                    </HeaderStyle>
                                    <ItemStyle Width="100%" HorizontalAlign="Right" VerticalAlign="Top" />
                                </telerik:GridButtonColumn>
                                <telerik:GridButtonColumn ButtonType="ImageButton" CommandName="Delete" FilterControlAltText="Filter DeleteColumn column"
                                    ImageUrl="Images/305_Close_16x16_72.png" Text="" UniqueName="DeleteColumn" Resizable="false"
                                    ConfirmText="Remove this athelete?" ConfirmDialogType="RadWindow" ConfirmTitle="Remove"
                                    ShowInEditForm="True">
                                    <HeaderStyle Wrap="False" HorizontalAlign="Left" Width="24px" CssClass="grid-header grid-header-last">
                                    </HeaderStyle>
                                    <ItemStyle Width="100%" HorizontalAlign="Right" VerticalAlign="Top" />
                                </telerik:GridButtonColumn>
                            </Columns>
                        </MasterTableView><EditItemStyle BackColor="Gainsboro" BorderStyle="None" />
                        <FooterStyle BorderStyle="None" />
                        <HeaderStyle BorderStyle="None" Height="48px" HorizontalAlign="Left" VerticalAlign="Middle" />
                        <CommandItemStyle CssClass="rgCommandRow" />
                        <ItemStyle BackColor="White" BorderStyle="None" ForeColor="Black" />
                        <PagerStyle PageSizeControlType="RadComboBox"></PagerStyle>
                        <SelectedItemStyle BorderStyle="None" />
                        <FilterMenu EnableImageSprites="False">
                        </FilterMenu>
                        <HeaderContextMenu CssClass="GridContextMenu GridContextMenu_Default">
                        </HeaderContextMenu>
                    </telerik:RadGrid>
                    <telerik:GridTextBoxColumnEditor ID="txtGridEdit_FirstName" runat="server" TextBoxStyle-Width="99%" />
                    <telerik:GridTextBoxColumnEditor ID="txtGridEdit_MiddleName" runat="server" TextBoxStyle-Width="99%" />
                    <telerik:GridTextBoxColumnEditor ID="txtGridEdit_LastName" runat="server" TextBoxStyle-Width="99%" />
                    <telerik:GridDropDownListColumnEditor ID="cmbGridEdit_Gender" runat="server" DropDownStyle-Width="100px" />
                    <telerik:GridDateTimeColumnEditor runat="server" ID="dtGridEdit_DoB" TextBoxStyle-Width="99%"  />
                    <telerik:GridTextBoxColumnEditor ID="txtGridEdit_Email" runat="server" TextBoxStyle-Width="99%"  />

Updated Javascript:
var bHasChanges = false;
var colUIInputItems = null;
var colDropdownLists = null;
var rowEditedItem = null;
var sAthleteGridID = "<%=grdAthletes.ClientID %>";
 
/// <summary>
/// Checks if the currently focused item is inside the grid.
/// </summary>
function IsItemInsideGrid() {
    var ret_bIsInGrid = false;
    var objCurItem = document.activeElement;
    var sObjectChain = "";
 
    if (objCurItem != null) {
        sObjectChain = objCurItem.id;
 
        //Keep looking at the object's parent object until the grid or top-most parent is found
        while (objCurItem.parentNode) {
            objCurItem = objCurItem.parentNode;
 
            if ((objCurItem != null) && (objCurItem.id.length > 0)) {
                sObjectChain += (" -> " + objCurItem.id);
 
                if (objCurItem.id.indexOf(sAthleteGridID) > -1) {
                    ret_bIsInGrid = true;
                    break;
                }
            }
        }
    }
 
    if (!ret_bIsInGrid) {
        //If currently editing a row, commit the changes and stop the editing
        if (rowEditedItem) {
            bHasChanges = false;
            $find(sAthleteGridID).get_masterTableView().updateItem(rowEditedItem);
 
 
            $find(sAthleteGridID).get_masterTableView().fireCommand("CancelAll", ""); //Cancel any editing activities in the grid
            $find(sAthleteGridID).get_masterTableView().clearSelectedItems(); //De-select any rows
        }
    }
 
    return ret_bIsInGrid;
}
 
/// <summary>
/// Handles the client side events when the athletes grid loses focus.
/// </summary>
function grdAthletes_LostFocus(sender, eventArgs) {
    setTimeout(IsItemInsideGrid, 50);
}
 
/// <summary>
/// Handles the client side RowClick event of the Athletes grid.
/// </summary>
function RowClick(sender, eventArgs) {
    //
}
 
/// <summary>
/// Handles the client side RowDblClick event of the Athletes grid.
/// </summary>
function RowDblClick(sender, eventArgs) {
    rowEditedItem = eventArgs.get_itemIndexHierarchical();
    $find(sAthleteGridID).get_masterTableView().editItem(rowEditedItem);
}
 
/// <summary>
/// Handles the client side GridCommand event of the Athletes grid.
/// </summary>
function GridCommand(sender, args) {
    if (args.get_commandName() != "Edit") {
        rowEditedItem = null;
    }
}
 
/// <summary>
/// Handles the client side GridCreated event of the Athletes grid.
/// </summary>
function GridCreated(sender, eventArgs) {
    var objGrid = sender.get_element();
    var arrUIObjects = [];
    var lowerType = null;
 
    colUIInputItems = objGrid.getElementsByTagName("input");
 
    //Set up change tracking for the input controls in the grid
    for (var iInputItems = 0; iInputItems < colUIInputItems.length; iInputItems++) {
        lowerType = colUIInputItems[iInputItems].type.toLowerCase();
 
        if ((lowerType == "hidden") || (lowerType == "button"))
            continue;
 
        if ((colUIInputItems[iInputItems].id.indexOf("PageSizeComboBox") == -1) && (colUIInputItems[iInputItems].type.toLowerCase() != "checkbox"))
            Array.add(arrUIObjects, colUIInputItems[iInputItems]);
 
        colUIInputItems[iInputItems].onchange = TrackChanges;
    }
 
    colDropdownLists = objGrid.getElementsByTagName("select");
 
    //Set up change tracking for the drop down controls in the grid
    for (var iDropDowns = 0; iDropDowns < colDropdownLists.length; iDropDowns++)
        colDropdownLists[iDropDowns].onchange = TrackChanges;
 
    setTimeout(function () { if (arrUIObjects[0]) arrUIObjects[0].focus(); }, 100);
}
 
/// <summary>
/// Handles the client side RowSelected event of the Athletes grid.
/// </summary>
function RowSelected(sender, eventArgs) {
    //If editing a row and changes are pending, commit the changes and stop the editing
    if (bHasChanges && rowEditedItem) {
        bHasChanges = false;
        $find(sAthleteGridID).get_masterTableView().updateItem(rowEditedItem);
    }
}
 
/// <summary>
/// Handles the client side Change event for controls in the Athletes grid.
/// </summary>
function TrackChanges(e) {
    bHasChanges = true;
}
 
/// <summary>
/// Handles the client side KeyPress event of the Athletes grid.
/// </summary>
function OnKeyPress(sender, args) {
    //Check for the Enter key being pressed
    if ((args._domEvent.charCode == 13) || (args.get_keyCode() == 13)) {
        //If currently editing a row, commit the changes and stop the editing
        if (rowEditedItem) {
            bHasChanges = false;
            $find(sAthleteGridID).get_masterTableView().updateItem(rowEditedItem);
        }
 
        $find(sAthleteGridID).get_masterTableView().fireCommand("UpdateAll", "");
    }
    else if ((args.get_keyCode() == 27) || (args._domEvent.charCode == 27)) //Check for the Esc key being press
    {
        $find(sAthleteGridID).get_masterTableView().fireCommand("CancelAll", ""); //Cancel any editing activities in the grid
        $find(sAthleteGridID).get_masterTableView().clearSelectedItems(); //De-select any rows
    }
}
 
/// <summary>
/// Handles the client side KeyPress event of the Athletes grid.
/// </summary>
function Email_OnKeyPress(sender, args) {
    var ret_bHandleEvent;
    var keyPressed;
 
    ret_bHandleEvent = true;
    args = (args || window.event);
    keyPressed = (args.which || args.keyCode || args._domEvent.charCode || args.get_keyCode());
 
    //Check for the Enter key being pressed
    if ((keyPressed == 9) && !args.shiftKey && !args.ctrlKey && !args.altKey) {
        //If currently editing a row, commit the changes and stop the editing
        if (rowEditedItem) {
            bHasChanges = false;
            $find(sAthleteGridID).get_masterTableView().updateItem(rowEditedItem);
        }
 
        $find(sAthleteGridID).get_masterTableView().fireCommand("UpdateAll", "");
        ret_bHandleEvent = false;
    }
 
    return ret_bHandleEvent;
}

Updated Grid event handling:
#region Grid events
 
protected void grdAthletes_PreRender(object sender, EventArgs e)
{
    try
    {
        CheckAtheleteTeamSize();
    }
    catch (Exception ex)
    {
        System.Diagnostics.Debug.Print("Error: " + ex.ToString());
        Exceptions.ProcessModuleLoadException(this, ex);
    }
}
 
protected void grdAthletes_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
{
    try
    {
        UpdateGridRowCounts();
 
        //Provide the current data for the grid to use
        grdAthletes.DataSource = _propsSettings.Records;
    }
    catch (Exception ex)
    {
        System.Diagnostics.Debug.Print("Error: " + ex.ToString());
        Exceptions.ProcessModuleLoadException(this, ex);
    }
}
 
protected void grdAthletes_UpdateCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
{
    this.UpdateGridItem((GridEditableItem)e.Item, true);
}
 
/// <summary>
/// Commits the specified row data to the underlying data source.
/// </summary>
/// <param name="UpdatedRow">The updated row data to commit.</param>
/// <param name="StartNewRow">Indicates if a new row should be created if the specified row is successfully updated.</param>
private void UpdateGridItem(GridEditableItem UpdatedRow, bool StartNewRow)
{
    Hashtable tblUpdatedValues = null;
    RadDropDownList ddlGenderCol = null;
 
    try
    {
        //Get the details of the item that needs to be updated
        tblUpdatedValues = new Hashtable();
 
        //Parse out the updated data
        UpdatedRow.OwnerTableView.ExtractValuesFromItem(tblUpdatedValues, UpdatedRow);
 
        ddlGenderCol = ((RadDropDownList)UpdatedRow.FindControl("ddlGender"));
 
        //Update the underlying data table with the updated information
        _propsSettings.Records.Rows[UpdatedRow.DataSetIndex]["FirstName"] = tblUpdatedValues["FirstName"].ToString();
        _propsSettings.Records.Rows[UpdatedRow.DataSetIndex]["MiddleName"] = tblUpdatedValues["MiddleName"].ToString();
        _propsSettings.Records.Rows[UpdatedRow.DataSetIndex]["LastName"] = tblUpdatedValues["LastName"].ToString();
 
        if (ddlGenderCol != null)
            _propsSettings.Records.Rows[UpdatedRow.DataSetIndex]["Gender"] = ddlGenderCol.SelectedValue;
        //_propsSettings.Records.Rows[UpdatedRow.DataSetIndex]["Gender"] = ((DropDownList)UpdatedRow.FindControl("ddlGender")).SelectedValue;
 
        _propsSettings.Records.Rows[UpdatedRow.DataSetIndex]["DoB"] = DateTime.Parse(tblUpdatedValues["DoB"].ToString()).ToString(@"M/d/yy");
        _propsSettings.Records.Rows[UpdatedRow.DataSetIndex]["ZipCode"] = tblUpdatedValues["ZipCode"].ToString();
        _propsSettings.Records.Rows[UpdatedRow.DataSetIndex]["Email"] = tblUpdatedValues["Email"].ToString();
        _propsSettings.Records.Rows[UpdatedRow.DataSetIndex]["RowCount"] = (UpdatedRow.DataSetIndex + 1);
 
        //Close out any open edit items and update the data displayed in the grid
        grdAthletes.MasterTableView.ClearEditItems();
        grdAthletes.Rebind();
 
        if (StartNewRow)
        {
            if ((_propsSettings.MaxTeamCount == 0) || (_propsSettings.Records.Rows.Count < _propsSettings.MaxTeamCount)) //Don't allow adding rows after the max
                CreateNewGridRow();
        }
    }
    catch (Exception ex)
    {
        System.Diagnostics.Debug.Print("Error: " + ex.ToString());
        Exceptions.ProcessModuleLoadException(this, ex);
    }
    finally
    {
        SaveControlState();
 
        //Clean up
        if (tblUpdatedValues != null)
        {
            tblUpdatedValues.Clear();
            tblUpdatedValues = null;
        }
 
        ddlGenderCol = null;
    }
}
 
protected void grdAthletes_EditCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
{
 
}
 
/// <summary>
/// Updates the RowCount field of the Athletes grid when users are added, deleted, or sorted.
/// </summary>
private void UpdateGridRowCounts()
{
    try
    {
        for (int iAthletes = 1; iAthletes <= _propsSettings.Records.Rows.Count; iAthletes++)
            _propsSettings.Records.Rows[iAthletes - 1]["RowCount"] = iAthletes;
    }
    catch (Exception ex)
    {
        System.Diagnostics.Debug.Print("Error: " + ex.ToString());
        Exceptions.ProcessModuleLoadException(this, ex);
    }
    finally
    {
        SaveControlState();
    }
}
 
/// <summary>
/// Creates a new row in the participants grid and puts it into Edit mode.
/// </summary>
private void CreateNewGridRow()
{
    try
    {
        UpdateGridRowCounts();
 
        //Close out any open edit items
        grdAthletes.MasterTableView.ClearEditItems();
 
        //Add the new row to the underlying data table
        AddNewRowInDataTable();
 
        //Select the new row and put it in edit mode
        grdAthletes.MasterTableView.Items[grdAthletes.MasterTableView.Items.Count - 1].Selected = true;
        grdAthletes.MasterTableView.Items[grdAthletes.MasterTableView.Items.Count - 1].Edit = true;
 
        //Update the grid to display the new row
        grdAthletes.Rebind();
    }
    catch (Exception ex)
    {
        System.Diagnostics.Debug.Print("Error: " + ex.ToString());
        Exceptions.ProcessModuleLoadException(this, ex);
    }
}
 
/// <summary>
/// Checks if the maximum number of athletes have been added and updates the UI to reflect it.
/// </summary>
/// <returns>A Boolean indicating if the maximum team size has been reached.</returns>
private bool CheckAtheleteTeamSize()
{
    bool ret_bReachedMax = false;
 
    try
    {
        if ((_propsSettings.MaxTeamCount == 0) || (_propsSettings.Records.Rows.Count < _propsSettings.MaxTeamCount)) //Don't allow adding rows after the max
            pnlMaxAthletesNote.Style["display"] = "none";
        else
        {
            ret_bReachedMax = true;
            lblMaxAthletes.Text = ("The maximum number of athletes for this team is " + _propsSettings.MaxTeamCount.ToString());
            pnlMaxAthletesNote.Style["display"] = "block";
        }
    }
    catch (Exception ex)
    {
        System.Diagnostics.Debug.Print("Error: " + ex.ToString());
        Exceptions.ProcessModuleLoadException(this, ex);
    }
 
    return ret_bReachedMax;
}
 
protected void grdAthletes_ItemCommand(object source, GridCommandEventArgs e)
{
    try
    {
        //Clear out any empty rows or bad data when a record has been canceled
        if (e.CommandName.Contains("Cancel"))
            CleanUpData();
        else if (e.CommandName.Contains("Delete"))
            UpdateGridRowCounts();
        else if (e.CommandName.Contains("UpdateAll"))
        {
            if ((grdAthletes.EditItems != null) && (grdAthletes.EditItems.Count > 0))
            {
                foreach (GridItem rowAthlete in grdAthletes.EditItems)
                    UpdateGridItem((GridEditableItem)rowAthlete, false);
            }
        }
 
        switch (e.CommandName)
        {
            case "UpdateAll":
            case "AddNewRow":
                if (!CheckAtheleteTeamSize()) //Don't allow adding rows after the max
                    CreateNewGridRow();
 
                break;
 
            default:
                break;
        }
    }
    catch (Exception ex)
    {
        System.Diagnostics.Debug.Print("Error: " + ex.ToString());
        Exceptions.ProcessModuleLoadException(this, ex);
    }
}
 
protected void grdAthletes_DeleteCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
{
    try
    {
        //Remove the row from the underlying data table
        _propsSettings.Records.Rows.RemoveAt(e.Item.DataSetIndex);
    }
    catch (Exception ex)
    {
        System.Diagnostics.Debug.Print("Error: " + ex.ToString());
        Exceptions.ProcessModuleLoadException(this, ex);
    }
    finally
    {
        SaveControlState();
    }
}
 
protected void grdAthletes_ItemDataBound(object sender, GridItemEventArgs e)
{
    Control ddlGenderSelector = null;
    Control ctrlFieldEditor = null;
    Control dtDoBEditor = null;
    Control ctrlFields = null;
 
    try
    {
        //Some controls don't load the values into the custom editor's automatically so force the values through
        if (e.Item.IsInEditMode)
        {
            ctrlFields = ((GridEditableItem)e.Item)["FirstName"].Controls[0];
            ((TextBox)ctrlFields).TabIndex = 50;
 
            ctrlFields = ((GridEditableItem)e.Item)["MiddleName"].Controls[0];
            ((TextBox)ctrlFields).TabIndex = 51;
 
            ctrlFields = ((GridEditableItem)e.Item)["LastName"].Controls[0];
            ((TextBox)ctrlFields).TabIndex = 52;
 
            ddlGenderSelector = e.Item.FindControl("ddlGender"); //Get the gender selection control
 
            //Load the current value for Gender into the column editor control
            if (ddlGenderSelector != null)
            {
                try
                {
                    ((RadDropDownList)ddlGenderSelector).SelectedValue = ((DataRowView)e.Item.DataItem)[3].ToString();
                    ((RadDropDownList)ddlGenderSelector).TabIndex = 53;
                }
                catch (Exception ex)
                { System.Diagnostics.Debug.Print("ERROR: " + ex.ToString()); }
            }
 
            //Set the min/max dates for athletes date of birth
            dtDoBEditor = ((GridEditableItem)e.Item)["DoB"].Controls[0];
 
            if (dtDoBEditor != null)
            {
                ((RadDatePicker)dtDoBEditor).TabIndex = 54;
 
                if (string.Compare(_propsSettings.ProgramCode, "Y", true) == 0)
                {
                    ((RadDatePicker)dtDoBEditor).SelectedDate = DateTime.Now.AddYears(-_propsSettings.MaxAge);
                    ((RadDatePicker)dtDoBEditor).MinDate = DateTime.Now.AddYears(-_propsSettings.MaxAge);
                }
                else
                {
                    ((RadDatePicker)dtDoBEditor).SelectedDate = DateTime.Now.AddYears(-_propsSettings.MinAge);
                    ((RadDatePicker)dtDoBEditor).MinDate = DateTime.MinValue;
                }
 
                if (_propsSettings.MinAge > 0)
                    ((RadDatePicker)dtDoBEditor).MaxDate = DateTime.Now.AddYears(-_propsSettings.MinAge);
                else
                    ((RadDatePicker)dtDoBEditor).MaxDate = DateTime.MaxValue;
 
                //Try to load the currently entered date, if it falls out of the available range, then select the minimum value
                try
                { ((RadDatePicker)dtDoBEditor).SelectedDate = DateTime.Parse(((DataRowView)e.Item.DataItem)[7].ToString()); }
                catch
                { ((RadDatePicker)dtDoBEditor).SelectedDate = ((RadDatePicker)dtDoBEditor).MinDate; }
            }
 
            ctrlFields = ((GridEditableItem)e.Item)["ZipCode"].Controls[0];
            ((RadMaskedTextBox)ctrlFields).TabIndex = 55;
            ((RadMaskedTextBox)ctrlFields).Width = 82;
 
            ctrlFields = ((GridEditableItem)e.Item)["Email"].Controls[0];
            ((TextBox)ctrlFields).TabIndex = 56;
            ((TextBox)ctrlFields).Width = 115;
            //((TextBox)ctrlFields).Attributes.Add("OnKeyPress", "return GridColKeyPress('" + ctrlFields.ClientID + "', event)");
            ((TextBox)ctrlFields).Attributes.Add("OnKeyDown", "return Email_OnKeyPress(this, event)");
 
            ctrlFields = ((GridEditableItem)e.Item)["DeleteColumn"].Controls[0];
            ((ImageButton)ctrlFields).TabIndex = -1;
 
            //Get the editor for the first field and set focus to it
            ctrlFieldEditor = ((GridEditableItem)e.Item)["FirstName"].Controls[0];
             
            if (ctrlFieldEditor != null)
                ctrlFieldEditor.Focus();
        }
    }
    catch (Exception ex)
    {
        System.Diagnostics.Debug.Print("Error: " + ex.ToString());
        Exceptions.ProcessModuleLoadException(this, ex);
    }
}
 
protected void grdAthletes_ItemCreated(object sender, GridItemEventArgs e)
{
    try
    {
        //Add the email validation handler
        if (e.Item is GridEditableItem && e.Item.IsInEditMode)
        {
            GridEditableItem item = e.Item as GridEditableItem;
            GridTextBoxColumnEditor editor = (GridTextBoxColumnEditor)item.EditManager.GetColumnEditor("Email");
            TableCell cell = (TableCell)editor.TextBoxControl.Parent;
            RegularExpressionValidator val = new RegularExpressionValidator();
 
            val.ControlToValidate = editor.TextBoxControl.ID;
            val.ValidationExpression = (@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
            val.ErrorMessage = "Invalid email address!";
            val.CssClass = "red";
            cell.Controls.Add(val);
        }
    }
    catch (Exception ex)
    {
        System.Diagnostics.Debug.Print("Error: " + ex.ToString());
        Exceptions.ProcessModuleLoadException(this, ex);
    }
}
 
/// <summary>
/// Adds a new row to the Athletes grid.
/// </summary>
private void AddNewRowInDataTable()
{
    DataRow drNewAthlete = null;
 
    try
    {
        drNewAthlete = _propsSettings.Records.NewRow();
 
        //Populate the default field values
        drNewAthlete["FirstName"] = string.Empty;
        drNewAthlete["MiddleName"] = string.Empty;
        drNewAthlete["LastName"] = string.Empty;
 
        if (string.Compare(_propsSettings.DefaultGender, "F", true) == 0)
            drNewAthlete["Gender"] = "Female";
        else
            drNewAthlete["Gender"] = "Male";
 
        if (string.Compare(_propsSettings.ProgramCode, "Y", true) == 0)
            drNewAthlete["DoB"] = DateTime.Now.AddYears(-_propsSettings.MaxAge);
        else
            drNewAthlete["DoB"] = DateTime.MinValue;
 
        drNewAthlete["Email"] = string.Empty;
        drNewAthlete["ZipCode"] = string.Empty;
        drNewAthlete["UniqueID"] = string.Empty;
        drNewAthlete["RowCount"] = (_propsSettings.Records.Rows.Count + 1);
 
        //Add the new row to the grid
        _propsSettings.Records.Rows.Add(drNewAthlete);
        grdAthletes.Rebind();
 
    }
    catch (Exception ex)
    {
        System.Diagnostics.Debug.Print("Error: " + ex.ToString());
        Exceptions.ProcessModuleLoadException(this, ex);
    }
    finally
    {
        SaveControlState();
    }
}
 
/// <summary>
/// Cleans up the Athletes grid data to make sure any invalid rows are removed.
/// </summary>
private void CleanUpData()
{
    try
    {
        if (_propsSettings.Records.Rows.Count > 0)
        {
            //Start at the end so that removing rows won't cause the index to be incorrect
            for (int iAthletes = (_propsSettings.Records.Rows.Count - 1); iAthletes > -1; iAthletes--)
            {
                try
                {
                    //Make sure all of the fields have valid data
                    if (string.IsNullOrEmpty(_propsSettings.Records.Rows[iAthletes][0].ToString()) || string.IsNullOrEmpty(_propsSettings.Records.Rows[iAthletes][2].ToString()) ||
                        string.IsNullOrEmpty(_propsSettings.Records.Rows[iAthletes][3].ToString()) || string.IsNullOrEmpty(_propsSettings.Records.Rows[iAthletes][4].ToString()))
                        _propsSettings.Records.Rows.RemoveAt(iAthletes); //Invalid data found, remove the row
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.Print("Error: " + ex.ToString());
                }
            }
        }
    }
    catch (Exception ex)
    {
        System.Diagnostics.Debug.Print("Error: " + ex.ToString());
        Exceptions.ProcessModuleLoadException(this, ex);
    }
    finally
    {
        SaveControlState();
    }
}
 
#endregion
Tags
Grid
Asked by
J
Top achievements
Rank 1
Answers by
J
Top achievements
Rank 1
Angel Petrov
Telerik team
Share this question
or