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();
}