Monday, March 26, 2012

Validating TextBoxes Created by Datagrid

I have a datagrid that creates textboxs for each row where a user can enter in an amount, the problem is if they enter text i get an error (Error converting data type varchar to float)so I will have to validate each textbox before submitting. Any ideas on how to do this or recommendations...

<datagrid id="dgAwards"...

<asp:TemplateColumn HeaderText="QTY" ItemStyle-HorizontalAlign="Center" ItemStyle-Width="5%">
<ItemTemplate>
<asp:TextBox ID="txtAwardAmnt" Runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "AWARD_AMOUNT") %>' Width="30pt">
</asp:TextBox>
</ItemTemplate>
</asp:TemplateColumn>

Thanks

Add validator into the ItemTemplate

<datagrid id="dgAwards"...

<asp:TemplateColumn HeaderText="QTY" ItemStyle-HorizontalAlign="Center" ItemStyle-Width="5%">
<ItemTemplate>
<asp:TextBox ID="txtAwardAmnt" Runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "AWARD_AMOUNT") %>' Width="30pt">
</asp:TextBox>

<asp:CompareValidator ID="cmpValtxtAwardAmnt" runat="server" ControlToValidate="txtAwardAmnt" Operator="DataTypeCheck" Type="Currency" ErrorMessage="Please specify a valid currency value" />

</ItemTemplate>
</asp:TemplateColumn>

Change the data type to match better the input you expect (for example, it could also be Integer). With RequiredFieldValidator you could make it mandatory for user to specify, or with RangeValidator to be in specified range with fixed min and max limits.

Note! In Server-side code you need to check Page.IsValid before running code dependant on validation to execute.

For more info see:Validating User Input in ASP.NET Web Pages


For some reason I was thinking this would of been a little more complicated so I didnt even think of attempting the obvious. :) Thanks.


hi...

i am designing a datagrid for the list of questions & I want only numbers and text only. while adding a question to the list, i validate it for a regular expression.but when i use the in-place edit function, i want to validate the same thing.The questions list should not have special characters...I know that i need to write a code for that in the UpdateCommand event which handles the update command.

can anyone please let me know how do i proceed.

thanks & regards

meera

No comments:

Post a Comment