2008/12/16

Gridview: automatically change focus from one TextBox to the other

In a word, I would like to do something like Excel can do:
1. After inputing data and pressing the "Enter" key, the focus should change to the next TextBox.
2. After focus changed, the content should be selected automatically so that users can repeat step 1.
3. Each "Enter" you press will trigger the postback and do some calculations.
4. If reach the end of the Gridview, do nothing.

Environment:
1.A GridView control + ASP.Net 2.0 application.
2.GridView has an ItemTemplate field, which contains TextBox.
3.GridView is inside an UpdatePanel.
protected void TextBox_TextChanged(object sender, EventArgs e)
{
  //get the parent gridview
  GridViewRow gvr = (GridViewRow)((TextBox)sender).NamingContainer;
  GridView gv = (GridView)gvr.NamingContainer;

  //automatically change focus to the next row's textbox
  if (gvr.RowIndex != gv.Rows.Count - 1)
   ChangeFocus((TextBox)gv.Rows[gvr.RowIndex + 1].FindControl(((TextBox)sender).ID), ScriptManager1);

  gvr = null;
  gv = null;
}

private static void ChangeFocus(TextBox tb, ScriptManager scriptMgr)
{
  tb.Attributes.Add("onfocus", "javascript:this.select();");
  scriptMgr.SetFocus(tb.ClientID);
}

No comments:

Post a Comment