UncleCoder.com

UncleCoder.com

Free programming examples and instructions

Validation control in Repeater

Demo and Code for how to use validation control in repeater Asp.net c#

by Athil


Posted on 25 Mar 2017 Category: Asp.net Views: 1558

Edited on 09 Aug 2017


DEMO

Here I am going to show how to use validation control in repeater control. Use Repeaters' ItemDataBound event for using validation in repeater. At the time of data binding ItemDataBound event will fire, For assigning control to validate for validation control I give a foreach loop to take each  textbox and validation control and assign validation controls' control to validate property to textbox id. 

Full Code

OnClient SIde

<form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
        <asp:Repeater ID="RptStud" runat="server" OnItemDataBound="RptStud_ItemDataBound">
            <ItemTemplate>
                <div>
                    Student Id: <%# Eval("Id") %>  <br />
                    student Name :  <asp:TextBox ID="txtName" Text= '<%# Eval("Name") %>' runat="server"></asp:TextBox> <br />
                    Score % : <asp:TextBox ID="txtScore" runat="server"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="Req1" ControlToValidate="txtScore" runat="server" ForeColor="Red" ErrorMessage="Required Score"></asp:RequiredFieldValidator> <br />
                    <hr/>
                    </div>

            </ItemTemplate>
        </asp:Repeater>
        <asp:Button ID="btnSubmit" runat="server" Text="Submit" />
    </div>
    </form>


    ​​​​​
On Server Side

protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                List<Student> students = new List<Student>();

                Student student = new Student();
                student.Id = 1;
                student.Name = "Stud1";
                students.Add(student);
                student = new Student();
                student.Id = 2;
                student.Name = "Stud2";
                students.Add(student);
                RptStud.DataSource = students;
                RptStud.DataBind();
            }
        }
        public class Student
        {
            public int Id { get; set; }
            public string Name { get; set; }
        }

        protected void RptStud_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            foreach (RepeaterItem item in RptStud.Items)
            {

                TextBox txtScore = item.FindControl("txtScore") as TextBox;
                RequiredFieldValidator validator = item.FindControl("Req1") as RequiredFieldValidator;
                validator.ControlToValidate = txtScore.ID;

            }
        }

 



Leave a Comment:


Advertisement