Tuesday, January 22, 2008

maintaining the tab order on page postback

The code to set focus to the next control after a postback is given below:
C#
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
WebControl wcICausedPostBack = (WebControl)GetControlThatCausedPostBack(sender as Page);
int indx = wcICausedPostBack.TabIndex;
var ctrl = from control in wcICausedPostBack.Parent.Controls.OfType<WebControl>()
where control.TabIndex > indx
select control;
ctrl.DefaultIfEmpty(wcICausedPostBack).First().Focus();
}
}
protected Control GetControlThatCausedPostBack(Page page)
{
Control control = null;
string ctrlname = page.Request.Params.Get("__EVENTTARGET");
if (ctrlname != null && ctrlname != string.Empty)
{
control = page.FindControl(ctrlname);
}
else
{
foreach (string ctl in page.Request.Form)
{
Control c = page.FindControl(ctl);
if (c is System.Web.UI.WebControls.Button || c is System.Web.UI.WebControls.ImageButton)
{
control = c;
break;
}
}
}
return control;
}

VB.NET
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Page.IsPostBack Then
Dim wcICausedPostBack As WebControl = CType(GetControlThatCausedPostBack(TryCast(sender, Page)), WebControl)
Dim indx As Integer = wcICausedPostBack.TabIndex
Dim ctrl = _
From control In wcICausedPostBack.Parent.Controls.OfType(Of WebControl)() _
Where control.TabIndex > indx _
Select control
ctrl.DefaultIfEmpty(wcICausedPostBack).First().Focus()
End If
End Sub
Protected Function GetControlThatCausedPostBack(ByVal page As Page) As Control
Dim control As Control = Nothing
Dim ctrlname As String = page.Request.Params.Get("__EVENTTARGET")
If ctrlname IsNot Nothing AndAlso ctrlname <> String.Empty Then
control = page.FindControl(ctrlname)
Else
For Each ctl As String In page.Request.Form
Dim c As Control = page.FindControl(ctl)
If TypeOf c Is System.Web.UI.WebControls.Button OrElse TypeOf c Is System.Web.UI.WebControls.ImageButton Then
control = c
Exit For
End If
Next ctl
End If
Return control
End Function

3 comments:

Unknown said...

This code rocks! I just dropped it in and it worked like a charm! Thanks!

Anonymous said...

C# version of the code works great. The VB.NET version has a problem with the Oftype: Dim ctrl = From control In wcICausedPostBack.Parent.Controls.OfType(Of WebControl)()

Anonymous said...

VB version is not working!!