Setting Focus in DataGrid - Solution

K

Kubuli John

I googled for a solution to this and didn't find a clear one, so I
thought I'd pass along what I ended up with.

In the PreRender event of the DataGrid, I execute the following code:

private void myGrid_PreRender(object sender, System.EventArgs e)
{
foreach (DataGridItem item in myGrid.Items)
{
foreach (Control ctl in item.Cells[0].Controls)
{
if (ctl.GetType() == typeof(System.Web.UI.WebControls.TextBox))
{
controlToFocus = ctl.UniqueID;
return;
}
}
}
}

In this method, controlToFocus is a page-level protected string. You
can customize the innermost foreach and if statements to find any
particular control you want to set the focus to - this example sets
the focus on the first TextBox it finds in the first column. Since I
only have TextBoxes when I'm ready to add or edit, this is fine.

Then, in the html, I have the following bits:

function setFocus()
{
ctl = "<%= controlToFocus %>";
if (ctl != "")
{
document.forms("my_form").elements(ctl).focus();
}
}

And:

<body onload="setFocus();">

Hope you find this useful...

John H.
 
Ø

Øystein Fallo

Excellent, John.

I've done alot of dirty workarounds to achive similar functionality.
Additionally, I would consider to emit the clientside-script using
Page.RegisterClientScriptBlock and Page.RegisterStartupScript:

Page.RegisterClientScriptBlock("SetFocus","<script
language=JavaScript>function setFocus(ctl,formname){if (ctl !=
""){document.forms("my_form").elements(ctl).focus();}}</script>");
Page.RegisterStartupScript("SetFocusStartup","<script
language=JavaScript>SetFocus('"+controlToFocus+"','my_form');</script>");

Or, maybe even better, encapsulate the entire thing in a custom control :)

rgds
Øystein Fallo
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,233
Members
46,820
Latest member
GilbertoA5

Latest Threads

Top