This example shows on how to get all server controls ID in the page using recursive FindControl.

Here are the code blocks below:

    protected void Page_Load(object sender, EventArgs e)

    {

        GetPageControlsID(Page);

    }

 

    public void GetPageControlsID(Control Parent)

    {

        string txBoxID = string.Empty;

        string ddListID = string.Empty;

        string lblID = string.Empty;

 

        System.Collections.Specialized.StringCollection strColTxtBoxID = new System.Collections.Specialized.StringCollection();

        System.Collections.Specialized.StringCollection strColDDListID = new System.Collections.Specialized.StringCollection();

        System.Collections.Specialized.StringCollection strCollblID = new System.Collections.Specialized.StringCollection();

 

        if (Parent is TextBox)

        {

            //Get the TextBox Control ID

            txBoxID = ((TextBox)Parent).ID;

            //then store the Control ID in a Collections

            strColTxtBoxID.Add(txBoxID);

        }

        else if (Parent is DropDownList)

        {

            //Get the DropDownLists Control ID

            ddListID = ((DropDownList)Parent).ID;

            strColDDListID.Add(ddListID);

        }

        else if (Parent is Label)

        {

            //Get the Labels Control ID

            lblID = ((Label)Parent).ID;

            strCollblID.Add(lblID);

        }

        else

        {

            foreach (Control c in Parent.Controls)

                GetPageControlsID(c);

        }

        //Just add some conditions here if you wan't to check for all other control types like

        //Button,ListBox, RadioButton, etc...

 

        //PRINT the Control ID's Collections that was found

 

        //Iterating through the TextBox Control ID's collections

        foreach (string id in strColTxtBoxID)

        {

            Response.Write(id + "<BR/>");

        }

 

        //Iterating through the DropDownList Control ID's collections

        foreach (string id in strColDDListID)

        {

            Response.Write(id + "<BR/>");

        }

 

        //Iterating through the Label Control ID's collections

        foreach (string id in strCollblID)

        {

            Response.Write(id + "<BR/>");

        }

 

    }

 

As you can see the code was pretty straight forward and self explanatory.

That’s it!

 

Technorati Tags: ,,