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

How to set focus to RadTextBox in RadGrid EditForm

11 Answers 733 Views
Input
This is a migrated thread and some comments may be shown as answers.
John Mann
Top achievements
Rank 1
John Mann asked on 19 Feb 2015, 10:38 PM
I have a RadGrid that uses an EditForm template in order to lay the controls out according to the wishes of the customer. I have not been able to get the RadTextBox within the template to receive focus when it goes into edit mode.
<telerik:RadGrid ID="rgComments" runat="server" AutoGenerateColumns="False" Width="100%" AllowSorting="True" CellSpacing="0" GridLines="None" Height="455px">
  <MasterTableView CommandItemDisplay="Top" CommandItemSettings-AddNewRecordText="Add Comment" CommandItemSettings-ShowRefreshButton="true" TableLayout="Fixed" EditMode="EditForms" DataKeyNames="iNoteID,qwImageID">
    <EditFormSettings EditFormType="Template">
      <FormTemplate>
        <div style="position: relative; height: 215px; width: 800px;">
          <telerik:RadTextBox ID="rtbComment" runat="server" Width="795px" Height="165px" ClientEvents-OnLoad="taComment_onload" />
          <asp:ImageButton ID="ibSave" runat="server" ImageUrl="~/Images/Save.png" CommandName='<%# (Container is GridEditFormInsertItem) ? "PerformInsert" : "Update" %>' style="position: absolute; left: 10px; top: 180px;" />
          <asp:ImageButton ID="ibCancel" runat="server" ImageUrl="~/Images/Cancel.png" CommandName="Cancel" style="position: absolute; left: 70px; top: 180px;" />
        </div>
      </FormTemplate>
    </EditFormSettings>
    <Columns>
      <telerik:GridEditCommandColumn ButtonType="ImageButton" HeaderStyle-Width="30px" ItemStyle-HorizontalAlign="Center" EditImageUrl="~/Images/Edit.png" UniqueName="gecEdit" />
      <telerik:GridBoundColumn DataField="dtCreateDate" HeaderText="Create Date" HeaderStyle-Width="66" HeaderStyle-HorizontalAlign="Center" DataFormatString="{0:MM/dd/yyyy HH:mm}" ReadOnly="True" UniqueName="gbc_dtCreateDate" />
      <telerik:GridBoundColumn DataField="cLoginName" HeaderText="Create By" HeaderStyle-Width="66" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center" ReadOnly="True" UniqueName="gbc_cLoginName" />
      <telerik:GridBoundColumn DataField="cNote" HeaderText="Comment" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Left" HeaderStyle-Width="500px" MaxLength="1024" UniqueName="gbc_cNote" />
      <telerik:GridButtonColumn ButtonType="ImageButton" CommandName="Delete" HeaderStyle-Width="30px" ItemStyle-HorizontalAlign="Center" ImageUrl="~/Images/Delete.png" UniqueName="bcDelete" />
    </Columns>
  </MasterTableView>
  <ClientSettings><Scrolling AllowScroll="true" /></ClientSettings>
</telerik:RadGrid>

When the form goes into edit mode I want to put the current Comment text into the RadTextBox and set focus there. I am using this code to try and do that.
void rgComments_ItemDataBound(object sender, GridItemEventArgs e)
{
  if (e.Item.IsInEditMode && e.Item is GridEditableItem)
  {
    GridEditableItem item = e.Item as GridEditableItem;
    RadTextBox radTextBox = ((RadTextBox)(((GridEditFormItem)(item)).FindControl("rtbComment")));
   
    // It works if I comment out this line, but then control is not populated with the necessary text
    radTextBox.Text = ((DataRowView)(((GridItem)(item)).DataItem)).Row["cNote"].ToString();
   
    radTextBox.Focus();
  }
}

I have tried adding a client-side onload event handler for the control to set the focus. It gets called but still won't put focus into the control.

Can you help me figure this out?

John

11 Answers, 1 is accepted

Sort by
0
Eyup
Telerik team
answered on 24 Feb 2015, 01:04 PM
Hello John,

You can use the following approach to achieve this requirement:
<telerik:RadTextBox ... Text='<%# Bind("ShipName") %>' OnLoad="rtbComment_Load" />
C#:
protected void rtbComment_Load(object sender, EventArgs e)
{
    (sender as RadTextBox).Focus();
}

Alternatively, you can do that on the client-side:
<telerik:RadTextBox ... Text='<%# Bind("ShipName") %>' ClientEvents-OnLoad="textBoxLoad" />
JavaScript:
function textBoxLoad(sender, args) {
    sender.focus();
}

You can also check the following live sample:
http://demos.telerik.com/aspnet-ajax/grid/examples/data-editing/form-template-update/defaultcs.aspx

Hope this helps.

Regards,
Eyup
Telerik
 

Check out the Telerik Platform - the only platform that combines a rich set of UI tools with powerful cloud services to develop web, hybrid and native mobile apps.

 
0
John Mann
Top achievements
Rank 1
answered on 24 Feb 2015, 06:03 PM
Thank you for the reply.

Unfortunately it hasn't fixed the problem. I can set focus using the method I had in my original question or either of the methods you provided as long as I don't put any text in the RadTextBox. It doesn't matter if I bind it, add it programmatically or even add static text. I can't both have focus on the control and populate it with text. The live sample you provided does not deal with setting focus on any of the controls. I don't know whether this is relevant, but the grid is in a web user control that is being displayed in a RadWindow.

It's a minor problem, but I am receiving lots of complaints from users about having to do an extra click before they can start typing. Any other suggestions?

Thanks,
John

0
Eyup
Telerik team
answered on 27 Feb 2015, 01:00 PM
Hi John,

I understand that it will be some effort, however, in order for us to assist you any further in this scenario, we will need you to send us an isolated runnable version of the project demonstrating the problematic behavior. Thus, we will be able to further analyze and debug the project and suggest a proper solution for your specific case.

In this sense, please open a formal support ticket to send us the aforementioned runnable web site sample.

Regards,
Eyup
Telerik
 

Check out the Telerik Platform - the only platform that combines a rich set of UI tools with powerful cloud services to develop web, hybrid and native mobile apps.

 
0
John Mann
Top achievements
Rank 1
answered on 19 Mar 2015, 10:54 PM
I will put together a sample program to demonstrate the problem when I am finished with my current project. I don't have the time to do it at the moment.
0
Eyup
Telerik team
answered on 24 Mar 2015, 01:01 PM
Hi John,

Please take your time as you can always reach us and send the sample in the formal support ticketing system any time.

Regards,
Eyup
Telerik
 

See What's Next in App Development. Register for TelerikNEXT.

 
0
jlj30
Top achievements
Rank 2
answered on 30 May 2016, 08:45 PM

Hi John,

Did you get this working?

I tried both techniques that Eyup recommended - the C# and the Javascript code.

Both looked reasonable and I had high hopes, but neither one worked.

I am running version 2016.2.504.45.

Thanks for any advice that you can offer.

Jim

0
John Mann
Top achievements
Rank 1
answered on 01 Jun 2016, 11:36 PM
I did not get it to work in my scenario. When I put together a test project I discovered that all the methods demonstrated above worked, until the radgrid was placed in a custom web user control.
0
Konstantin Dikov
Telerik team
answered on 02 Jun 2016, 02:44 PM
Hello Jim,

Could you please elaborate on your exact scenario and the RadGrid configuration. You could also share the exact code that you have tested in regards of the focusing.

Looking forward to your reply.


Regards,
Konstantin Dikov
Telerik
Do you need help with upgrading your ASP.NET AJAX, WPF or WinForms projects? Check the Telerik API Analyzer and share your thoughts.
0
jlj30
Top achievements
Rank 2
answered on 09 Jun 2016, 12:44 PM

Hi Konstantin,

Some background.

The C# code below worked in version 2015.3.1111.45, but no longer has any effect in 2016.2.504.45.

protected void grdControls_ItemCreated(object sender, GridItemEventArgs e)
{
    try
    {
        if (e.Item is GridEditableItem && e.Item.IsInEditMode)
        {
            CommonMethods.SetRaygunData("System Action", "Place focus on first field", ref _raygunCustomData);
            var item = (GridEditableItem)e.Item;
            var txtName = item.FindControl("txtName") as RadTextBox;
            if (txtName == null)
            {
                CommonMethods.ClearRaygun(RayTitle, ref _raygunTags, ref _raygunCustomData);
                return;
            }
            var script =
                string.Format("setTimeout(function(){{var c = $get('{0}'); if(c && c.focus) c.focus();}},1);",
                    txtName.ClientID);
            ScriptManager.RegisterStartupScript(Page, typeof(Page), "key", script, true);
        }
        if (_isExport && e.Item is GridFilteringItem)
        {
            e.Item.Visible = false; // Hide the filter row when exporting
        }
        CommonMethods.ClearRaygun(RayTitle, ref _raygunTags, ref _raygunCustomData);
    }
    catch (Exception ex)
    {
        HandleError(ex);
    }
}

I came across this thread and thought perhaps I had found an alternate way of setting focus, but no luck.

Here's my RadGrid declaration:

<telerik:RadGrid ID="grdControls" ClientSettings-Resizing-AllowColumnResize="true" PageSize="20" Width="100%" ShowStatusBar="True" DataSourceID="sqlControls"
                 runat="server" AutoGenerateColumns="False" AllowSorting="True" AllowPaging="False"
                 GridLines="None" Skin="Vista" ClientSettings-Selecting-AllowRowSelect="True"
                 AllowAutomaticDeletes="True" AllowAutomaticInserts="True" AllowAutomaticUpdates="True"
                 AllowMultiRowSelection="True" OnItemInserted="grdControls_ItemInserted" ClientSettings-Scrolling-AllowScroll="true"
                 ClientSettings-Scrolling-UseStaticHeaders="true" ClientSettings-Scrolling-ScrollHeight="100%"
                 OnItemCommand="grdControls_ItemCommand" OnItemUpdated="grdControls_ItemUpdated"
                 OnItemDataBound="grdControls_ItemDataBound" OnPreRender="grdControls_PreRender" OnItemCreated="grdControls_ItemCreated"
                 AllowFilteringByColumn="True" OnInfrastructureExporting="grdControls_InfrastructureExporting">
<ExportSettings
    HideStructureColumns="True"
    IgnorePaging="True"
    OpenInNewWindow="True"
    ExportOnlyData="True">
    <Excel Format="Xlsx" DefaultCellAlignment="Left"></Excel>
</ExportSettings>
<GroupingSettings CaseSensitive="false"/>
<MasterTableView DataSourceID="sqlControls" DataKeyNames="ID" AllowMultiColumnSorting="True"
                 CommandItemDisplay="Top" AllowAutomaticDeletes="True"
                 AllowAutomaticInserts="True" AllowAutomaticUpdates="True" EditMode="PopUp" ClientDataKeyNames="ID">
    <CommandItemTemplate>
        <div style="float: left;">
            <asp:LinkButton ID="lnkNew" runat="server" CommandName="InitInsert" Visible='<%# (bool) Session["EditProcess"] %>'><img style="border: 0px" alt="" src="Images/Fast Icon Images/documents.png"/> New Control</asp:LinkButton>
            <asp:LinkButton ID="lnkNewFromCommon" runat="server" OnClientClick="openRadWindow('winAddCommon;Select Common Items;625;450');return false;" autopostback="false"
                            Visible='<%# (bool) Session["EditProcess"] %>'>
                <img style="border: 0px" alt="" src="Images/Fast Icon Images/documents.png"/> New From Common
            </asp:LinkButton>
            <asp:LinkButton ID="lnkDelete" OnClientClick="javascript:return confirm('Delete all selected Controls?');"
                            runat="server" CommandName="DeleteSelected" Visible='<%# (bool) Session["EditProcess"] %>'>
                <img style="border: 0px" alt="" src="Images/Fast Icon Images/file_cancel.png"/> Delete Selected
            </asp:LinkButton>
            <asp:LinkButton ID="lnkReOrder" runat="server" OnClientClick="openRadWindow('winReOrder;Re-Order Controls;400;400');return false;" autopostback="false"
                            Visible='<%# (bool) Session["EditProcess"] %>'>
                <img style="border: 0px" alt="" src="Images/Fast Icon Images/bt_refresh.png"/> Re-Order
            </asp:LinkButton>
        </div>
        <div style="float: right; text-align: right;">
            <asp:Label ID="lblRecordCount" runat="server" Text=""></asp:Label>
            <asp:LinkButton ID="ExportToExcelButton" runat="server" CommandName="X2X"><img style="border: 0px" alt="" src="Images/Excel.png"/> Export To Excel</asp:LinkButton>
            <asp:LinkButton ID="lnkRefresh" runat="server" CommandName="Refresh"><img style="border: 0px" alt="" src="Images/Fast Icon Images/refresh2.png"/> Refresh</asp:LinkButton>
        </div>
    </CommandItemTemplate>
 
    <RowIndicatorColumn FilterControlAltText="Filter RowIndicator column">
    </RowIndicatorColumn>
    <ExpandCollapseColumn Visible="True" FilterControlAltText="Filter ExpandColumn column">
    </ExpandCollapseColumn>
    <Columns>
        <telerik:GridClientSelectColumn FilterControlAltText="Filter column column" UniqueName="selControl" Exportable="False">
            <FooterStyle HorizontalAlign="Center"/>
            <HeaderStyle HorizontalAlign="Center" Width="40px"/>
            <ItemStyle HorizontalAlign="Center"/>
        </telerik:GridClientSelectColumn>
        <telerik:GridTemplateColumn HeaderText="Edit" UniqueName="editColumn" AllowFiltering="false" Exportable="False">
            <ItemTemplate>
                <asp:ImageButton ID="btnUpdateOrView" ImageUrl='<%# (bool) Session["EditProcess"] ? "~/images/Fast Icon Images/edit.png" : "~/images/Fast Icon Images/search.png" %>'
                                 runat="server" CommandName="Edit">
                </asp:ImageButton>
            </ItemTemplate>
            <FooterStyle HorizontalAlign="Center"/>
            <HeaderStyle HorizontalAlign="Center" Width="40px"/>
            <ItemStyle HorizontalAlign="Center"/>
        </telerik:GridTemplateColumn>
        <telerik:GridBoundColumn SortExpression="Name" HeaderText="Name" HeaderButtonType="TextButton"
                                 DataField="Name" UniqueName="Name" AllowFiltering="True" AllowSorting="True" CurrentFilterFunction="Contains" AutoPostBackOnFilter="true" FilterControlWidth="50%">
            <HeaderStyle Width="25%"/>
        </telerik:GridBoundColumn>
        <telerik:GridBoundColumn SortExpression="Description" HeaderText="Description" HeaderButtonType="TextButton"
                                 DataField="Description" UniqueName="Description" AllowFiltering="True" AllowSorting="True" CurrentFilterFunction="Contains" AutoPostBackOnFilter="true" FilterControlWidth="50%">
            <HeaderStyle Width="65%"/>
        </telerik:GridBoundColumn>
        <telerik:GridTemplateColumn HeaderText="Common" AllowFiltering="true" SortExpression="Common_Flag"
            UniqueName="Common_Flag_Column" FilterControlWidth="85px" DataField="Common_Flag">
            <ItemTemplate>
                <asp:Image ID="imgCommon" runat="server" ImageAlign="Middle" ImageUrl="~/Images/Fast Icon Images/bt_apply_16x16.png"
                    Visible='<%# Eval("Common_Flag") %>' AlternateText='<%# Eval("Common_Flag") %>'/>
            </ItemTemplate>
            <HeaderStyle HorizontalAlign="Center" Width="10%"></HeaderStyle>
            <ItemStyle HorizontalAlign="Center"></ItemStyle>
        </telerik:GridTemplateColumn>
    </Columns>
    <EditFormSettings InsertCaption="New Control" CaptionFormatString="Editing Control"
                      CaptionDataField="Description" PopUpSettings-Modal="true" EditFormType="Template">
        <EditColumn FilterControlAltText="Filter EditCommandColumn column">
        </EditColumn>
        <FormTemplate>
            <div id="divControlEdit" runat="server" class="formTemplate">
                <table class="formTemplateTable">
                    <tr>
                        <td class="templateLabel">
                            <telerik:RadButton ID="btnAddUpdate" runat="server" Text='<%# (bool) DataBinder.Eval(Container, "OwnerTableView.IsItemInserted") ? "Create" : "Update" %>'
                                               Visible='<%# (bool) Session["EditProcess"] %>' CommandName='<%# (bool) DataBinder.Eval(Container, "OwnerTableView.IsItemInserted") ? "PerformInsert" : "Update" %>'>
                            </telerik:RadButton>
                            <telerik:RadButton ID="btnCancel" runat="server" Text='<%# (bool) Session["EditProcess"] ? "Cancel" : "Close" %>'
                                               CausesValidation="False" CommandName="Cancel">
                            </telerik:RadButton>
                        </td>
                        <td class="templateValue">
                            <telerik:RadSpell ID="RadSpell1" runat="server" ButtonType="PushButton" ButtonText="Spell Check"
                                              ControlsToCheck="txtName,txtDesc" SupportedLanguages="en-US,English" Visible='<%# (bool) Session["EditProcess"] %>'/>
                            <asp:Label ID="lblReadOnly" runat="server" Text="** READ ONLY **" class="readOnly"
                                       Visible='<%# !(bool) Session["EditProcess"] %>'>
                            </asp:Label>
                        </td>
                    </tr>
                    <tr>
                        <td class="templateLabel">
                            <asp:Label ID="lblName" runat="server" Text="Name:" class="required" ToolTip="Provide a brief and meaningful name for this Control"></asp:Label>
                            <asp:Label ID="lblReqName" runat="server" Text=" *" class="requiredAsterisk" Visible='<%# (bool) Session["EditProcess"] %>'></asp:Label>
                        </td>
                        <td class="templateValue">
                            <telerik:RadTextBox ID="txtName" TabIndex="1" MaxLength='<%# (int) Session["MaxSingleLineSize"] %>' runat="server" Text='<%# Bind("Name") %>' Width="450px" onkeydown="return (event.keyCode!=13);"
                                                ToolTip="Provide a brief and meaningful name for this Control" Enabled='<%# (bool) Session["EditProcess"] %>'>
                            </telerik:RadTextBox>
                            <asp:RequiredFieldValidator runat="server" ID="valName" ControlToValidate="txtName"
                                                        ErrorMessage="**Required**" Enabled='<%# (bool) Session["EditProcess"] %>'>
                            </asp:RequiredFieldValidator>
                        </td>
                    </tr>
                    <tr>
                        <td class="templateLabel">
                            <asp:Label ID="lblDesc" runat="server" Text="Description:" class="required" ToolTip="Provide a detailed description of this Control"></asp:Label>
                            <asp:Label ID="lblReqDesc" runat="server" Text=" *" class="requiredAsterisk" Visible='<%# (bool) Session["EditProcess"] %>'></asp:Label>
                        </td>
                        <td class="templateValue">
                            <telerik:RadTextBox ID="txtDesc" TabIndex="2" MaxLength='<%# (int) Session["MaxMultiLineSize"] %>' runat="server" Text='<%# Bind("Description") %>'
                                                Width="450px" Rows="7" TextMode="MultiLine" ToolTip="Provide a detailed description of this Control"
                                                Enabled='<%# (bool) Session["EditProcess"] %>'>
                            </telerik:RadTextBox>
                            <asp:RequiredFieldValidator runat="server" ID="valDesc" ControlToValidate="txtDesc"
                                                        ErrorMessage="**Required**" Enabled='<%# (bool) Session["EditProcess"] %>'>
                            </asp:RequiredFieldValidator>
                        </td>
                    </tr>
                    <tr>
                        <td class="templateLabel">
                            <asp:Label ID="lblCommon" runat="server" Text="Common:" ToolTip="Check this box if this Control may be suitable for use in other processes"></asp:Label>
                        </td>
                        <td class="templateValue">
                            <telerik:RadButton ID="chkCommon" TabIndex="3" runat="server" ButtonType="ToggleButton" ToggleType="CheckBox"
                                               AutoPostBack="false" Checked='<%# Bind("Common_Flag") %>' ToolTip="Check this box if this Control may be suitable for use in other processes" onkeydown="return (event.keyCode!=13);"
                                               Enabled='<%# (bool) Session["EditProcess"] %>'>
                            </telerik:RadButton>
                        </td>
                    </tr>
                    <telerik:RadNumericTextBox ID="numListOrder" runat="server" Text='<%# Bind("ListOrder") %>'
                                               Visible="false">
                    </telerik:RadNumericTextBox>
                </table>
            </div>
        </FormTemplate>
    </EditFormSettings>
</MasterTableView>
<ClientSettings EnableRowHoverStyle="true" AllowKeyboardNavigation="true">
    <ClientEvents OnPopUpShowing="PopUpCentered" OnRowSelecting="RowSelecting" OnKeyPress="OnKeyPress"/>
    <Selecting AllowRowSelect="True"></Selecting>
    <Scrolling AllowScroll="True" UseStaticHeaders="True"></Scrolling>
    <Resizing AllowColumnResize="true" ResizeGridOnColumnResize="true" AllowResizeToFit="true" />
</ClientSettings>
<FilterMenu EnableImageSprites="False">
</FilterMenu>
</telerik:RadGrid>

 

Any thoughts on how to get this working again?

We're getting complaints from users :(

Thanks for any suggestions or code snippets.

Jim

0
Konstantin Dikov
Telerik team
answered on 14 Jun 2016, 11:18 AM
Hello Jim,

The code that you are using is working correctly, but only if you increase the time in the setTimeout function (to 200 for example). I would personally recommend that you handle this on client-side, within the pageLoad event, which will ensure that the focus will not be lost:
function pageLoad(){
   /// finding the element through the grid's API
   /// focusing the inpuit
}

Hope this helps.


Regards,
Konstantin Dikov
Telerik
Do you need help with upgrading your ASP.NET AJAX, WPF or WinForms projects? Check the Telerik API Analyzer and share your thoughts.
0
jlj30
Top achievements
Rank 2
answered on 14 Jun 2016, 01:05 PM

Thanks Konstantin,

I had to increase the timeout value to 300 to make it work, but it does work.

I'll investigate the client side solution as well.

Thanks for a solution.

JIm

Tags
Input
Asked by
John Mann
Top achievements
Rank 1
Answers by
Eyup
Telerik team
John Mann
Top achievements
Rank 1
jlj30
Top achievements
Rank 2
Konstantin Dikov
Telerik team
Share this question
or