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.