UncleCoder.com

UncleCoder.com

Free programming examples and instructions

Asp.net - Validation control in repeater

Demo and code for how to use validation control in repeater

by Athil


Posted on 01 Jan 0001 Category: Asp.net Views: 328

Edited on 01 Jan 0001


Here I am going to show how we can use validation control in a repeater control.

DEMO

For this, I created one repeater with two Textboxes, for Name and Score For the score Textbox I am using required field validator, If I didn't give any value to that text box and click on submit button, It will show the message as 'required score'.

Client side

          <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" />

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