I have FormView and on changing to Edit mode I wanted to set focus to the first textbox. I thought I’d do this hooking into the ModeChanged event but this doesn’t work as the textbox hasn’t been rendered.
I then tried overriding the Render method and setting the focus after rendering; at this point the control was created but I get an exception to say focus can only be set in PreRender, but in PreRender the control won’t be available.
One way I found to get this to work was to set the focus in a handler for the DataBound event of the FormView.
protected void fvUser_DataBound(object sender, EventArgs e)
{
Control ctrl = fvUser.FindControl("txtForename");
if (ctrl != null)
{
ctrl.Focus();
}
}
Another way to do it is by adding client side JavaScript at the bottom of the EditItemTemplate which is run after the control has been created:
...
<script type="text/javascript" language="javascript">
document.getElementById('<%= fvUser.FindControl("txtForename").ClientID %>').focus();
</script>
</EditItemTemplate>


