Big
Bang
Indians
PROUD TO BE INDIANS

Tuesday, September 18, 2007

ASP.NET : GridView - Set focus to control and select full text on the edited row

Sorry for not posting anything since last few days, actually I have loaded myself with loads of development.

You will find lots of my post on GridView, JavaScript, DetailsView and FormView. I am working on DataGrid and GridView since its early days and have done extensive programming on it.

For the question on setting focus on textbox and select full in the edit template of the GridView control, here is my offer:

For example, we have two textbox TextBox1 and TextBox2 as TemplateField.
Now, when user click on edit button then selected GridView row turns into edit mode and the TextBox1 should get focus with all its text selected by default. If user moves on to TextBox2 then again its text should get selected.
Code:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
TextBox tmpText1 = ((TextBox)(e.Row.FindControl("textbox1")));
TextBox tmpText2 = ((TextBox)(e.Row.FindControl("textbox2")));

if (e.Row.RowState == DataControlRowState.Edit e.Row.RowState.ToString() == "Alternate, Edit")
{
// Set the focus to control on the edited row in reverse, last column in
// GridView should come first here.

tmpText2.Focus();
tmpText2.Attributes["onfocus"] = "javascript:this.select();";

tmpText1.Focus();
tmpText1.Attributes["onfocus"] = "javascript:this.select();";

}
}

I would be more than happy to answer any question / queries.

No comments: