Sunday, August 9, 2009

Validating a Textbox in Grid View Using JavaScript

In this post I will show you how to validate a textbox placed in template field of grid view
Say for eg, we have grid view listing Currency and Exchange rate
Where the exchange is in textbox field where you the user can change it
Now we will validate for the currency

If the Currency Code is USD then the exchange rate should not be less that of 3.665

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" >
<Columns>
<asp:BoundField DataField="Currency" HeaderText="Currency" />
<asp:TemplateField HeaderText="Exchg Rate" >
<ItemTemplate>
<asp:TextBox ID="txtExchgRate" runat="server" ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>



Code Behind

Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound

If e.Row.RowType = DataControlRowType.DataRow Then

If e.Row.Cells(0).Text = "USD" Then
CType(e.Row.Cells(1).FindControl("txtExchgRate"), TextBox).Attributes.Add("onblur", "fnValUSDExchg(this)")
End If

End If

End Sub


JavaScript Function

<script language="javascript" type="text/javascript">

function fnValUSDExchg(txtbox)
{
if (txtbox.value<=3.665)
txtbox.value=3.665;
}
</script>

Low Maintenance - Impossible to fix if broken.

No comments:

Post a Comment