Monday, March 19, 2012

Another way to create dynamic controls in Asp.net


Few months back,I am already wrote many articles on Dynamic Controls in Asp.net like How to create Dynamic Regisration form, How to apply validations for Dynamic Controls  and  How to save data in Database from Dynamic Controls .
This time i would like to explain a bit easier way to implement dynamic controls compare to previous article by using Repeater control.Here we are going create two controls which accepts customer name and mobile no and applying required field validator.

dynamic controls





Lets start the process

First,choose one new Asp.net website from Templates

Next,Drag ad Drop one Repeater Control from Toolbox which is under Data Group in Toolbox

Next Add the Item templates in order the Textbox controls and at the same time add the Required field validations..
See the below code





        
 Customer Name:


 
                           
 Mobile:






                

     
Next Add one Button, to check whether the Textbox's are empty or filled with data in the button click Event..

Next Add one link Button ,to add dynamic controls in link button Event

Next,Open the .cs page and write the following method in page load.That is

BindTemplate()

Write the following code inside the BindTemplate()
private void BindTemplate()        
        {
        Repeater1.DataSource = ControlsList;
        Repeater1.DataBind();
        }
        
        private List ControlsList
        {
        get
        {
            if (ViewState["ControlsList"] != null)
            {
                return ViewState["ControlsList"] as List;
            }
            else
            {
                List _tmpList = new List();
                _tmpList.Add(_tmpList.Count);
                ViewState["ControlsList"] = _tmpList;
                return _tmpList;
            }
        }
        set
        {
            ViewState["ControlsList"] = value;
        }
        }
        
 
Next Write the following code to add dynamic controls in the link button event

protected void AddOneRow_Click(object sender, EventArgs e)
        {
        List _tmpList = ControlsList;
        _tmpList.Add(_tmpList.Count);
        ViewState["ControlsList"] = _tmpList;
        BindTemplate();
        }
        


Next Write the following code to Check Validations for dynamic controls in the submit button event

protected void btnSubmit_Click(object sender, EventArgs e)
        {
        Page.ClientScript.RegisterStartupScript(typeof(Page), "alert", ""); 
        }
        



Note : Add this namespace 

using System.Collections.Generic;
 
That's it..In the Next article I am going to explain How to save the Data in database from this dynamically created controls

Labels: , , , , ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home