简体   繁体   中英

How to validate asp.net textbox inside grid view

I am trying to validate asp textbox inside grid-view but my challenge is that i have 3 item templates in my aspx page,

ID
Question
Answer

i want to put some validation on the Answer field where users have to enter specific answer only based on the ID. If ID = 1 then they can only enter age number like 1 to 99. If ID = 2 then they can only enter some kind height values like 5.3, 5.8 etc. Here is how my current grid view look like

<asp:GridView ID="GV_Test" runat="server"  
                    AutoGenerateColumns="False"
                    ShowFooter="True" DataKeyNames="ID">
                    <Columns>

                        <asp:TemplateField  HeaderText="Question ID" Visible="true">
                            <ItemTemplate>
                                <asp:Label ID="lblQST_SK" runat="server" Text='<%# Eval("ID")%>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>


                        <asp:TemplateField ItemStyle-Width="150px" HeaderText="Questions">
                            <ItemTemplate>
                                <asp:Label ID="lblQuestions" runat="server" Text='<%# Eval("Question")%>'></asp:Label>
                            </ItemTemplate>                                
                        </asp:TemplateField>

                        <asp:TemplateField HeaderText="Answer">                              
                                <ItemTemplate>                               
                                  <asp:TextBox ID="txtAn" runat="server" CssClass="form-control" Text='<%# Eval("Answer")%>' ></asp:TextBox>
                            </ItemTemplate>
                        </asp:TemplateField>

                    </Columns>

                </asp:GridView>

How can i resolve this issue? thanks

You could add onkeypress to your itemtemplate like below:

<asp:TextBox ID="txtAn" runat="server" CssClass="form-control" Text='<%# Eval("Answer")%>' onkeypress='<%#"DecideHowToValidateThisID("+ Eval("Id") +");"%>' ></asp:TextBox>

write a javascript function "DecideHowToValidateThisID(id)" and based on the id you get as input you can decide how to validate that textbox.

This approach works if u have a small set of predefined ID's along with how to validate


The best way would be to have an itemdatabound event for your grid - find out what validation is to be done and add that to your row

Check out this link for an example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM