Sunday 27 September, 2009

Simple tips: Set Focus to TextBox in GridView (edit mode)


If you use TemplateField like


            
                
             
            
                
             
        


 You could do it in RowEditing, for example:

protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            //Normal turning to edit
            GridView1.EditIndex = e.NewEditIndex; 
            BindGrid();

            //Set the focus to control on the edited row
            GridView1.Rows[e.NewEditIndex].FindControl("txtEdit").Focus();
        }

I'm binding the grid manually, therefore there is setting the index and calling databinding functions. However, with BoundField (I have CommandField as left most column) it could be something like:

GridView1.Rows[e.NewEditIndex].Cells[1].Controls[0].Focus();

where Cells[index] is the one you should be modifying based on which column it is in question (still doing in RowEditing)
In case you use data-source controls, it might be feasible to do it in RowDataBound:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowState == DataControlRowState.Edit)
            {
                //Set the focus to control on the edited row
                e.Row.Cells[1].Controls[0].Focus(); 
                //Or to a specific control in TemplateField
               // e.Row.FindControl("txtEdit").Focus(); 
            }
        } 

No comments:

Post a Comment