Add RequiredField Validator to dynamic TextBoxes in ASP.Net GridView Rows using C# and VB.Net

Last Reply one month ago By dharmendr

Posted one month ago

Hi , 

Thank you for your great code. Really appreciate it. Helps me a lot.

As per you sample below:

Maximum Row Validation when adding dynamic Rows to GridView on Button Click in ASP.Net

How do I add Validation for empty fields when submitting data ?

Posted one month ago

Hi sathish75,

Change the html with the below.

HTML

<asp:GridView ID="Gridview1" runat="server" ShowFooter="true" AutoGenerateColumns="false"
    OnRowCreated="Gridview1_RowCreated">
    <Columns>
        <asp:BoundField DataField="RowNumber" HeaderText="Row Number" />
        <asp:TemplateField HeaderText="Header 1">
            <ItemTemplate>
                <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
                <asp:RequiredFieldValidator ControlToValidate="TextBox1" ErrorMessage="Required"
                    runat="server" Display="Dynamic" ValidationGroup="G1" ForeColor="Red"></asp:RequiredFieldValidator>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Header 2">
            <ItemTemplate>
                <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
                <asp:RequiredFieldValidator ControlToValidate="TextBox2" ErrorMessage="Required"
                    runat="server" Display="Dynamic" ValidationGroup="G1" ForeColor="Red"></asp:RequiredFieldValidator>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Header 3">
            <ItemTemplate>
                <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
                <asp:RequiredFieldValidator ControlToValidate="TextBox3" ErrorMessage="Required"
                    runat="server" Display="Dynamic" ValidationGroup="G1" ForeColor="Red"></asp:RequiredFieldValidator>
            </ItemTemplate>
            <FooterStyle HorizontalAlign="Right" />
            <FooterTemplate>
                <asp:Button ID="ButtonAdd" runat="server" Text="Add New Row" OnClick="ButtonAdd_Click"
                    ValidationGroup="G1" />
            </FooterTemplate>
        </asp:TemplateField>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:LinkButton ID="LinkButton1" runat="server" OnClick="LinkButton1_Click">Remove</asp:LinkButton>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>
<asp:Button ID="Button1" runat="server" Text="Save" OnClick="Button1_Click" ValidationGroup="G1" />