0

I have a GridView in page that holds a TextBox, which I would like to set focus. This GridView is wrapped in a UpdatePanel. The problem is the TextBox can only be set focus from the post back control event, but not from Page Load. Code looks like this:

aspx:

<asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="server" ChildrenAsTriggers="true">    
  <Triggers>                                                     
     <asp:AsyncPostBackTrigger ControlID="btnUpdate" />                                                    
  </Triggers>    
  <asp:GridView ID="Grid" runat="server" AutoGenerateColumns="False">
   ...
    <asp:TemplateField HeaderText="Date">
      <ItemTemplate>                                                                                      
        <asp:TextBox ID="txtDate" runat="server"></asp:TextBox>
      </ItemTemplate>
    </asp:TemplateField>

</asp:UpdatePanel>

aspx.cs:

protected void Page_Load(object sender, EventArgs e)
{
  if(!IsPostBack)
  {
    ShowGrid(); //This does not set focus
  }
} 

protected void btnUpdate_Click(object sender, EventArgs e)
{
  ShowGrid(); //This works OK
}

private void ShowGrid()
{
  Grid.DataSource = _datatable;
  Grid.DataBind();

  GridViewRowEventArgs e = new GridViewRowEventArgs(Grid.Rows[0]);
  TextBox txtDate = (TextBox)e.Row.FindControl("txtDate");
  if (txtDate != null) //when debugging txtDate is not null from Page Load
    Page.SetFocus(txtDate); 
}

I have tried all solutions in this post but none of them worked for my scenario. Is it having something to do with page event sequence?

I guess several lines of JavaScript/jQuery after DOM ready will still do the job but I am trying to find a way to get this to work through backend code.

wctiger
  • 921
  • 12
  • 22
  • `txtDate.Focus()` this doesn't work..? also you are aware that button clicks trigger PostBacks.. and will call the web pages `Pag_Load` event.. – MethodMan Nov 13 '17 at 22:04
  • I could not replicate the issue in my environment. It is possible that something else in your code is causing the issue. Which element is getting the focus instead of the TextBox? What happens if you remove the control that is getting the focus? – Mike Mat Nov 13 '17 at 22:49
  • Tested your code and it works. The TextBox gets focus both on page load and a PostBack. Maybe there is a script interfering somewhere – VDWWD Nov 14 '17 at 07:46
  • @MikeMat Thanks for trying this out. Looks like the focus was actually removed when page loads because document.activeElement returns body at that time. – wctiger Nov 14 '17 at 17:36
  • @VDWWD Also thanks for trying it. I've been looking at my other scripts for a few hours but didn't find anything yet. But that does sound like where the problem came from so I'll see if I find it – wctiger Nov 14 '17 at 17:38

0 Answers0