Tuesday, October 6, 2009

ASP Grid View Focus on Text Box in Edit Mode

I've seen a bunch of examples of how to focus in on a GridView's textbox while in edit mode but every one I saw involved a bunch of code & an item template.

The basic idea I came up with was to acomplish the same thing through javascript. This process takes a little bit of manual work to find out the name of the control that you want.


1st: I added a method for the RowDataBound event so the text box I wanted actually existed when I was looking for it's ID.

protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)

2nd: I had 12 columns in my grid view and I wanted to focus in on the last column's text box so I used the 11th control in the row to get the generated name of the control i needed.

string controlID = e.Row.Controls[11].ClientID;

3rd: I then had to replace the last two characters in the string with 00. (I'm not sure if this will change for you, thats what makes it a manual process for the first time. After the page loaded, I just did a view source on the HTML to see what changed in the name of the button object.)

controlID = controlID.Substring(0, controlID.Length - 2) + "00";

4th: replace the underscore's with dollar signs.

controlID = controlID.Replace('_', '$');

LAST: Put the following javascript in a label or in the innerHtml of a panel.
lblJavaScriptPOST.Text = "<script type="text\javascript">document.getElementById('" + controlID + "').focus()</script>"

So... here is all of the code for my gridview's row data bound event method.

protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
//If this current row being bound is in the edit state, set focus to something
if (e.Row.RowState == DataControlRowState.Edit || (e.Row.RowState == (DataControlRowState.Edit |DataControlRowState.Alternate)))
{

string controlID = e.Row.Controls[11].ClientID;
controlID = controlID.Substring(0, controlID.Length - 2) + "00";
controlID = controlID.Replace('_', '$');

lblJavaScriptPOST.Text = "<script type="text\javascript">document.getElementById('" + controlID + "').focus()</script>";
}

}

This is a lot less code than using a template item and if you don't/can't use template items. It's the only way that I know of doing this.

Hope this helps someone!

2 comments:

Anonymous said...

I found this site using [url=http://google.com]google.com[/url] And i want to thank you for your work. You have done really very good site. Great work, great site! Thank you!

Sorry for offtopic

Anonymous said...

First, thanks.
I would not do any manual work!
If you are looking to get the control name, then, it could be done through the the code behinde - namely, RowDataBound. I would have created a hidden field where I can store the name of the control that needs to be set on focus.
No chance to loose the focus. Correct me if I am wrong. Thanks