How to set focus in Texbox on closing predefined dialog box



I have created a text box. On GotFocus event, I open a predefined dialog. On closing dialog, Gotfocus sould not fired again and focus should set to text box to input value.


How to catch dialog close event on pressing ESC and Cancel key


I have added my code here:


builder.AddAttribute(renderctr++, "Focus", Microsoft.AspNetCore.Components.EventCallback.Factory.Create<Syncfusion.Blazor.Inputs.FocusInEventArgs>(this, args => GotFocus(args, Obj.CtrlName, Obj.DispName, MstCtrls)));



public async Task GotFocus(Syncfusion.Blazor.Inputs.FocusInEventArgs args, string CtrlName, string DispName, List<ModObjs> Ctrls )

{

    DispName = string.IsNullOrEmpty(DispName) ? CtrlName : DispName;

    var Obj = Ctrls.FirstOrDefault(o => o.CtrlName+"/"+o.DispName == CtrlName+"/"+DispName);

    if (Obj != null)

    {

        if (Obj.IsListOfCtrl && !Obj.IsPrimitiveType)

        {

            OpnLstOnFld = CtrlName +"/"+ DispName;

            FldValidation VldObj = AllFldValidations.FirstOrDefault(o => o.FldName == CtrlName+"/"+DispName);

            if (VldObj != null)

            {

                ShowSearchGrid = true;

                await OpenSearchGrid(VldObj, args.Value, Ctrls);



            }

        }

    }

}


 private async Task OpenSearchGrid( FldValidation VldObj, string DefVal, List<ModObjs> Ctrls )

 {

     if (true)//(!FocusSet)

     {

         string FldName = VldObj.FldName;

         string ListOf = VldObj.ListOf;

         string LinkModName = VldObj.LinkModName;

         string ObjValCond = "";


         ObjValCond = PrepareSeachGridCond(VldObj);


         SearchGridTitle = "Select " + FldName.Split("/")[1] + "...";

         GetTableData oTblData = new GetTableData

         {

             Query = ListOf,

             ModName = ModName,

             QueryType = "SG",

             PrimeIdConnStr = Global.MainDBConnStr,

             SQLConnStr = CompConnStr,

             SelectClause = FldName,

             WhereCond = ObjValCond,

             AddPK = true

         };

         string json = JsonConvert.SerializeObject(oTblData);

         var response = await RazorFunc.CallAPIAsync(Global.APIURL, "GetDynaModData", json);

         var respStatusCode = response.StatusCode;

         if (respStatusCode.ToString() == "OK")

         {

             var responseBody = await response.Content.ReadAsStringAsync();

             var retJSON = JsonConvert.DeserializeObject<RetJSON>(responseBody);

             if (retJSON.Status.ToString() == "Error")

             {

                 await sfDialogService.AlertAsync(retJSON.Msg.ToString() + retJSON.ExError, CoreVars.ERROR);

             }

             else

             {

                 GridColStru = JsonConvert.DeserializeObject<List<SQLTblFldDef>>(retJSON.AdtData.ToString().Trim());

                 DataTable DataTbl = JsonConvert.DeserializeObject<DataTable>(retJSON.Data.ToString().Trim());

                 List<string> HiddenCol = new List<string>();

                 DataTable HiddenColDt = JsonConvert.DeserializeObject<DataTable>(retJSON.ModAdtData.ToString().Trim());

                 if (DataTbl.Rows.Count > 0)

                 {

                     ShowSearchGrid = true;

                     foreach (DataRow row in HiddenColDt.Rows)

                     {

                         HiddenCol.Add(row["FldName"].ToString());

                     }

                     GridColsBuilderSG = RazorFunc.CreateGridColumns(GridColStru, HiddenCol, "PKFld", new List<string>(), new List<string>());

                     SearchGridData = RazorFunc.DataTblToExpandoObj(DataTbl);

                 }

                 else

                 {

                     await sfDialogService.AlertAsync("No record(s) found.", CoreVars.ERROR);

                     ShowSearchGrid = false;

                 }

             }

         }

         else

         {

             await sfDialogService.AlertAsync(response.ReasonPhrase, CoreVars.ERROR);

         }


         if( ShowSearchGrid){

             bool Selected = await sfDialogService.ConfirmAsync(null, SearchGridTitle, new DialogOptions()

             {

                 ChildContent =

                 @<div >

                 @if (ShowSearchGrid)

                 {

                     <div class="display-top-bar">

                         <div class="search-wrap">

                             <SfTextBox @ref="SearchGridTxt" class="e-control e-textbox e-lib e-input" placeholder="Search..." ShowClearButton="true"

                             Input='((e) => SearchInGridAJ(e, SearchGrid))'></SfTextBox>

                         </div>

                         <div class="display-inline-btns">

                             <SfButton IconCss="e-icons e-file-new" title="Add new entry" @onclick="()=>AddOnlineNewItem(LinkModName)"></SfButton>

                             <SfButton IconCss="e-icons e-refresh" title="Refresh"></SfButton>

                         </div>

                     </div>

                     <SfGrid @ref="SearchGrid" DataSource="@SearchGridData" GridLines="GridLine.Both" RowHeight="@CoreVars.ROWHEIGHT" EnableStickyHeader="true">

                         <GridEvents RowSelected="SGRowSelectHandler" OnRecordDoubleClick="SGRecordDoubleClickHandler" TValue="ExpandoObject"

                             OnDataBound="()=> DataBoundHandler(DefVal)"></GridEvents>

                         <GridSelectionSettings EnableToggle="false"></GridSelectionSettings>

                         <GridColumns>

                             @GridColsBuilderSG

                         </GridColumns>

                     </SfGrid>

                  }

                 else

                 {

                     @RenderOnlineEntryPage

                 }

                 </div>

 ,

                 ShowCloseIcon = true,

                 AllowDragging = true, CloseOnEscape = true, Width = "800", Height = "500",

                 PrimaryButtonOptions= new DialogButtonOptions(){ Content="Select", IconCss="e-icons e-check" },

                 CancelButtonOptions = new DialogButtonOptions() { Content = "Cancel", IconCss = "e-icons e-close" },

                 //AnimationSettings = new DialogAnimationOptions( ) { Effect =DialogEffect.Zoom}

             });


             if (Selected)

             {

                 ProcessSelectedRecord(Ctrls, VldObj.DetQry);

             }

             else

             {

                 // var SetFocusObj = MstCtrls.FirstOrDefault(o => o.CtrlName == OpnLstOnFld.Split("/")[0]);

                 // if( SetFocusObj != null )

                 // {

                 // await SetFocusObj.TextCtrl.FocusAsync();

                 // SetFocusObj.DecimalNumberCtrl.Foc

                 // StateHasChanged();

                 // }


                 // //SetFocusAJ(null, OpnLstOnFld.Split("/")[0], "M");

                 // FocusSet = true;

             }

         }

     }

 }


Attachment: text_928416b.zip

1 Reply

YV Yaswin Vikhaash Rajaretenam Syncfusion Team February 26, 2025 05:23 PM UTC

Hi Amish,

We have validated your query, and you can achieve the desired behavior where the dialog closes without re-triggering the GotFocus event while ensuring the focus is set back to the text box.

To implement this, you can use two flag variables—one to track the dialog’s open state and another to manage focus without reopening the dialog.

Please refer to the code snippet below for a detailed implementation:

@using Syncfusion.Blazor.Inputs
@using Syncfusion.Blazor.Popups
@inject SfDialogService DialogService

<div style="margin: 150px auto; width: 50%">
    <SfTextBox @ref="textBoxRef" Focus="@FocusHandler"></SfTextBox>
</div>

@code {
    private bool IsOpened { get; set; } = false;
    private bool IsManualFocus { get; set; } = false; // Flag to track manual focus
    private SfTextBox textBoxRef;

    private async Task FocusHandler(FocusInEventArgs args)
    {
        if (IsManualFocus)
        {
            IsManualFocus = false; // Reset flag to allow normal focus handling
            return; // Prevent opening the dialog when focus is set manually
        }

        if (!IsOpened)
        {
            IsOpened = true; // Set flag before opening the dialog to prevent re-entry
            bool isConfirmed = await DialogService.ConfirmAsync("Content", "SearchGridTitle", new DialogOptions()
                {
                    ShowCloseIcon = true,
                    AllowDragging = true,
                    CloseOnEscape = true,
                    Width = "800",
                    Height = "500",
                    PrimaryButtonOptions = new DialogButtonOptions() { Content = "Select", IconCss = "e-icons e-check" },
                    CancelButtonOptions = new DialogButtonOptions() { Content = "Cancel", IconCss = "e-icons e-close" }
                });

            await HandleDialogClose(); // Call this method after dialog closes
        }
    }

    private async Task HandleDialogClose()
    {
        IsOpened = false; // Reset flag after dialog is closed
        await Task.Delay(100); // Small delay to avoid immediate retriggering

        IsManualFocus = true; // Set flag to prevent reopening dialog
        await textBoxRef?.FocusAsync(); // Manually set focus back to the textbox
    }
}

Regards,

Yaswin Vikhaash


Attachment: Textbox_with_predefined_dialog_5176c7f4.zip

Loader.
Up arrow icon