Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

How to set focus in a GridView

4 views
Skip to first unread message

ad

unread,
May 17, 2005, 3:21:15 AM5/17/05
to
I used ASP.NET 2.0.
When I edit a row in a GridView.
How can I set the focus to the first editable column?


Brock Allen

unread,
May 17, 2005, 1:23:21 PM5/17/05
to
You might want to handle the OnRowDataBound event from the GridView:

protected void _grid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && (e.Row.RowState
& DataControlRowState.Edit) != 0)
{
Control c = e.Row.Cells[2].Controls[0];
this.SetFocus(c);
}
}

The trick is to know which column in e.Row.Cells and then which control in
that Cell's Controls collectiono to set focus on.

-Brock
DevelopMentor
http://staff.develop.com/ballen

Toby

unread,
Jun 15, 2005, 7:19:10 AM6/15/05
to
You cound also try

Public Shared Sub SetFocus(ByVal control As Control)
If control.Page Is Nothing Then
Throw New ArgumentException("The Control must be added to a Page
before you can set the IntialFocus to it.")
End If
'If the control is enabled and visible select it
If control.Visible And control.EnableViewState Then
If control.Page.Request.Browser.JavaScript = True Then
' Create JavaScript
Dim s As StringBuilder = New StringBuilder
s.Append(vbCrLf + "<SCRIPT LANGUAGE='JavaScript'>" + vbCrLf)
s.Append("<!--" + vbCrLf)
s.Append("function SetInitialFocus()" + vbCrLf)
s.Append("{" + vbCrLf)
s.Append(" try " & vbCrLf)
s.Append(" {" & vbCrLf)
s.Append(" document.")
' Find the Form
Dim p As control = control.Parent
While Not (TypeOf p Is System.Web.UI.HtmlControls.HtmlForm)
p = p.Parent
End While
s.Append(p.ClientID)
s.Append("['")
s.Append(control.UniqueID)
' Set Focus on the selected item of a RadioButtonList
If TypeOf control Is RadioButtonList Then
Dim rbl As RadioButtonList = control
If Not rbl Is Nothing Then
Dim suffix As String = "_0"
Dim t As Int32 = 0
Dim li As ListItem
For Each li In rbl.Items
If li.Selected Then
suffix = "_" + t.ToString()
Exit For
End If
t = t + 1
Next
s.Append(suffix)
End If
End If
' Set Focus on the first item of a CheckBoxList
If TypeOf control Is CheckBoxList Then
s.Append("_0")
End If
s.Append("'].focus();" + vbCrLf)
s.Append(" }catch(e){}" & vbCrLf) ' close the try, catch
block
s.Append("}" + vbCrLf)
If control.Page.SmartNavigation Then
s.Append("window.setTimeout(SetInitialFocus, 500);" +
vbCrLf)
Else
s.Append("window.onload = SetInitialFocus;" + vbCrLf)
End If
s.Append("// -->" + vbCrLf)
s.Append("</SCRIPT>" + vbCrLf)
' Register Client Script
control.Page.RegisterClientScriptBlock("InitialFocus",
s.ToString())
End If
End If
End Sub

"ad" <a...@wfes.tcc.edu.tw> wrote in message
news:OnOUFErW...@TK2MSFTNGP12.phx.gbl...

0 new messages