Is it possible to put focus back on a gridview row after that a selection of the row generates a postback?
I’m trying to add an onkeydown handler on the gridview rows in order to use the keyboard for navigation. My problem, I believe, is that after the first postback, the selected cell loses focus, and so the next key stroke is not caught by the cell.
I have the following code
The grid view
<asp:GridView runat="server" ID="gdvPersons" AutoGenerateColumns="false"
onrowcreated="gdvPersons_RowCreated" onselectedindexchanged="gdvPersons_SelectedIndexChanged">
<Columns>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<%# ((GridviewFocus.Person) Container.DataItem).Name %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Age">
<ItemTemplate>
<%# ((GridviewFocus.Person) Container.DataItem).Age %>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
The Code behind
protected void Page_Load(object sender, EventArgs e)
{
var persons = new List<Person> {new Person() {Name = "Fikre", Age = 24},
new Person() {Name = "Mike", Age = 29},
new Person() {Name = "Mark", Age = 35}};
gdvPersons.DataSource = persons;
gdvPersons.DataBind();
}
protected void gdvPersons_RowCreated(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
e.Row.Attributes.Add("onkeydown", ClientScript.GetPostBackEventReference((Control)sender, "Select$" + e.Row.DataItemIndex));
}
protected void gdvPersons_SelectedIndexChanged(object sender, EventArgs e)
{
gdvPersons.SelectedRow.Focus();
}
On your onkeydown script code copy the id of the cell to a hidden input field.
the example above is plain html, and you would have to add the proper onkeydown code to your gridview.
In your postback (for example onclick) event handler code you can retrieve the id from the hidden fields value property and register javascript to execute once the page is refreshed. If you have a button which is clicked which performs the postback you could do something like this:
This should make your page execute the following script once it’s loaded, and the control should retrive focus: