Wednesday, July 28, 2010

Set Focus to Textbox in Gridview inside Update Panel

Let’s see how to set focus to textbox inside Gridview inside Update Panel.

So the Gridview is designed something like this..

<asp:UpdatePanel ID="UpdatePanel1" runat="server">

<ContentTemplate>

<asp:GridView ID="gvattend" runat="server" CellPadding="5"

AutoGenerateColumns="false" AllowPaging="true" PageSize="50"

GridLines="none" HeaderStyle-CssClass="tableheadbg" BorderStyle="solid" RowStyle-CssClass="nestedtable" AlternatingRowStyle-CssClass="nestedtable1"

BorderColor="#a3b4a0" BorderWidth="1px" Width="100%" TabIndex="6" >

<Columns>

<asp:TemplateField HeaderText="Marks Obtained" >

<ItemTemplate>

<asp:Textbox id="txtmarksobtain" runat="server" Width="150" AutoPostBack="true" OnTextChanged=" txtmarksobtain _TextChanged" >asp:Textbox>

ItemTemplate>

asp:TemplateField>

<asp:TemplateField HeaderText="Percentage" >

<ItemTemplate>

<asp:Textbox id="txtpercentage" runat="server" Width="150" Enabled="false" >asp:Textbox>

<asp:CompareValidator ID="cmp3" runat="server" ControlToValidate="txtpercentage" Operator="DataTypeCheck" Type="Double" ErrorMessage="Enter Numeric Value Alone" Display="dynamic" ValidationGroup="subject">asp:CompareValidator>

ItemTemplate>

asp:TemplateField>

Columns>

<EmptyDataTemplate>

<table width="100%" cellpadding="5" cellspacing="5">

<tr><td align="center" valign="middle" ><span class="redcolor">No Data Foundspan> td>tr>

table>

EmptyDataTemplate>

<RowStyle CssClass="nestedtable" />

<HeaderStyle CssClass="tableheadbg" />

<AlternatingRowStyle CssClass="nestedtable1" />

asp:GridView>

ContentTemplate>

asp:UpdatePanel>

And in the Code Behind:

Protected Sub txtmarksobtain _TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtmaxmarks.TextChanged

For Each gv As GridViewRow In gvattend.Rows

Dim txtmarksobtain As TextBox = DirectCast(gv.FindControl("txtmarksobtain"), TextBox)

If txtmarksobtain.Text = "" Then

ScriptManager.RegisterStartupScript(Me, Me.GetType(), "selectAndFocus", "$get('" + txtmarksobtain.ClientID + "').focus();$get('" + txtmarksobtain.ClientID + "').select();", True)

End If

Next

End Sub

And thus focus is set to textbox inside Gridview