Dynamic Page Creation in asp.net (Controls from database)

Unknown | 9:12 PM |

using System;
using System.Collections.Generic;
using System. Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using gAero;
using System.Text;
using AjaxControlToolkit;
using System.Data.Objects;
using System.Data;
using System.Reflection;

namespace gAero
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        gAeroEntities gAE = new gAeroEntities();

        protected void Page_PreInit(Object sender, EventArgs e)
        {
            
        }
        protected void Page_PreRender(Object sender, EventArgs e)
        {

        }
        protected void Page_Load(object sender, EventArgs e)
        {
          
                StringBuilder strBuilderJS = new StringBuilder();
               
             //function openwindow(prodid) { window.open("test.aspx?id=" + prodid, "null",
            //"width=350,height=300,scrollbars=yes,left=350,top=200,right=5,bottom=5");  return false; } function InitComponents(flag) 
            //{ $("[id$=hdfDDL_Country]").val("");   var pageURL = window.document.URL;  var virtualPath = "";   
            //var url = pageURL.replace(location.pathname, virtualPath == "" ? "/LoadStates.ashx" : "/" + virtualPath + "LoadStates.ashx"); 
            //if (url.indexOf("?") !== -1)    url = url.substring(0, url.indexOf("?")); 
            //GrandScriptUtils.MakeAutoComplete("DDL_Country", url, "hdfDDL_Country", true, true, "COUNTRY");
            //GrandScriptUtils.MakeAutoComplete("DDL_Location", url + "?Country=" + ($("[id$=hdfDDL_Country]").val() == "" 
            //|| $("[id$=hdfDDL_Country]").val() == "0" ||    $("[id$=hdfDDL_Country]").val() == "-1" ? "-1" : $("[id$=hdfDDL_Country]").val()),
            //"hdfDDL_Location", true, true, "STATE");   }   function AfterAutoCompleteSelect(targetControlID) {  
            //if (targetControlID == "DDL_Country") {    $("[id$=hdfDDL_Location]").val("0");   $("[id$=DDL_Location]").val("Select/Type");
            //var pageURL = window.document.URL;  var virtualPath = "";             
            //var url = pageURL.replace(location.pathname, virtualPath == "" ? "/LoadStates.ashx" : "/" + virtualPath + "LoadStates.ashx");
            //if (url.indexOf("?") !== -1) url = url.substring(0, url.indexOf("?"));  
            //GrandScriptUtils.MakeAutoComplete("DDL_Location", url + "?Country=" + ($("[id$=hdfDDL_Country]").val() == ""
            //|| $("[id$=hdfDDL_Country]").val() == "0" ||  $("[id$=hdfDDL_Country]").val() == "-1" ? "-1" : $("[id$=hdfDDL_Country]").val()),
            //"hdfDDL_Location", true, true, "STATE"); } } function AfterInvalidSelect(targetControlID) {if (targetControlID == "DDL_Country") 
            //{ $("[id$=hdfDDL_Location]").val("0");  $("[id$=DDL_Location]").val("Select/Type");  var pageURL = window.document.URL; 
            //var virtualPath = "";  var url = pageURL.replace(location.pathname, virtualPath == "" ? "/LoadStates.ashx" : 
            //"/" + virtualPath + "LoadStates.ashx");  if (url.indexOf("?") !== -1) url = url.substring(0, url.indexOf("?")); 
            //GrandScriptUtils.MakeAutoComplete("DDL_Location", url + "?Country=-1", "hdfDDL_Location", true, true, "ASSET");  
            //} }$(document).ready(function() {  InitComponents(); jQuery.validator.addMethod(  "CustomDate",  function(value, element) 
            //{  return value.match(/\b\d{1,2}[\/-]\d{1,2}[\/-]\d{4}\b/);    },     "Please enter valid date "     ); 
            //$.validator.addMethod("dateRange", function(value, element) {  var fullDate = new Date(); 
            //var twoDigitMonth = (fullDate.getMonth()+1)+""; if(twoDigitMonth.length==1)  twoDigitMonth="0" +twoDigitMonth; 
            //var twoDigitDate = fullDate.getDate()+""; if(twoDigitDate.length==1) twoDigitDate="0" +twoDigitDate; 
            //var currentDate = twoDigitDate + "-" + twoDigitMonth + "-" + fullDate.getFullYear();  return (value >= currentDate); },
            //"Please specify a correct date range."); $("#form1").validate({  rules: {   
            //ctl00$MainContent$tabcEmpManage$Tab_EmployeeBasic$Txt_EmpName : {     required: true  }, 
            //ctl00$MainContent$tabcEmpManage$Tab_EmployeeBasic$DTM_DOJ : {     required: true,CustomDate: true ,dateRange: true       }, 
            //ctl00$MainContent$tabcEmpManage$Tab_EmployeeBasic$NUM_Salary : {  required: true  }   }, messages: 
            //{  ctl00$MainContent$tabcEmpManage$Tab_EmployeeBasic$Txt_EmpName:{ required: "Enter Name "   },
            //ctl00$MainContent$tabcEmpManage$Tab_EmployeeBasic$DTM_DOJ:{  required: "Enter Date of Join ",date:"Enter Valid Date"    },  
            //ctl00$MainContent$tabcEmpManage$Tab_EmployeeBasic$NUM_Salary:{  required: "Enter Salary "     }     }     });  });

                string PageScript = (from ScriptDtl in gAE.AD_FieldScript_Dtl
                                     where ScriptDtl.Fls_Page == 1
                                     select ScriptDtl.Fls_Script).SingleOrDefault();
                int len = PageScript.Length;

                ScriptManager.RegisterStartupScript(this, typeof(Page), "pagescript", PageScript, true);

                if (!IsPostBack)
                {
                    BindTabControls();
                    BindPageControls(tabcEmpManage.ActiveTab.ID);
                }
          
            
        }

        protected void tabcEmpManage_ActiveTabChanged(object sender, EventArgs e)
        {
            
        }

        private void BindTabControls()
        {
            var TabControls = from Tabs in gAE.AD_Tabs_Mst
                              join TabsMaps in gAE.AD_PageTab_Mpg
                              on Tabs.Tab_PK equals TabsMaps.PTM_Tab
                              join Pages in gAE.AD_Pages_Mst
                              on TabsMaps.PTM_Page equals Pages.Pge_PK
                              where Pages.Pge_PK == 1
                              select new
                              {
                                  Tabs.Tab_Id,
                                  Tabs.Tab_DispName
                              };

           

            foreach (var tab in TabControls)
            {
                TabPanel tp = new TabPanel();
                tp.ID = tab.Tab_Id;
                tp.HeaderText = tab.Tab_DispName;
                tabcEmpManage.Controls.Add(tp);
            }

        }

        private void BindPageControls(string  TabId)
        {
            int TabPk = (from Tabs in gAE.AD_Tabs_Mst
                          where Tabs.Tab_Id == TabId
                          select Tabs.Tab_PK).SingleOrDefault();

            int Cols = (from TabsMaps in gAE.AD_PageTab_Mpg
                        where TabsMaps.PTM_Tab == TabPk
                        select TabsMaps.PTM_Cols).SingleOrDefault();


            var FieldControls = from Tabs in gAE.AD_Tabs_Mst
                                join PageMaps in gAE.AD_PageTab_Mpg on Tabs.Tab_PK equals PageMaps.PTM_Tab
                                join Pages in gAE.AD_Pages_Mst on PageMaps.PTM_Page equals Pages.Pge_PK
                                join Fields in gAE.AD_Fields_Mst on Tabs.Tab_PK equals Fields.Fld_Tab
                                join Controls in gAE.AD_Controls_Cfg on Fields.Fld_Control equals Controls.Ctl_PK
                                where Tabs.Tab_Id == TabId 
                                orderby Fields.Fld_Order
                                   select new
                                   {                                       
                                       Fields.Fld_PK,
                                       Fields.Fld_Id,
                                       Fields.Fld_Name,
                                       Fields.Fld_DispName,
                                       Fields.Fld_Control,
                                       Fields.Fld_DDL_DataSource,
                                       Fields.Fld_Order,
                                       Fields.Fld_Description,
                                       Fields.Fld_Active,
                                       Controls.Ctl_PK,
                                       Controls.Ctl_Id,
                                       Controls.Ctl_Name,
                                       Controls.Ctl_Class,
                                       Controls.Ctl_Active
                                   };


            Table tbControls = new Table();

           DataTable dtFieldControls=LINQToDataTable(FieldControls);

           int k = 0;

           if (dtFieldControls.Rows.Count > 0)
           {
               for (int i = 0; i <= dtFieldControls.Rows.Count; i++)
               {

                   TableRow trControls = new TableRow();

                   for (int j = 0; j < Cols; j++)
                   {
                       if (dtFieldControls.Rows.Count > 0)
                       {
                           TableCell tcControl1 = new TableCell();
                           TableCell tcControl2 = new TableCell();

                           int FieldPk = int.Parse(dtFieldControls.Rows[k]["Fld_PK"].ToString());

                           string Event = (from ScriptDtl in gAE.AD_FieldScript_Dtl
                                           where ScriptDtl.Fls_Field == FieldPk
                                           select ScriptDtl.Fls_Event).SingleOrDefault();

                           string Script = (from ScriptDtl in gAE.AD_FieldScript_Dtl
                                            where ScriptDtl.Fls_Field == FieldPk
                                            select ScriptDtl.Fls_Script).SingleOrDefault();



                           tcControl1.Controls.Add(new Label()
                           {
                               ID = "lbl" + dtFieldControls.Rows[k]["Fld_DispName"].ToString(),
                               Text = dtFieldControls.Rows[k]["Fld_DispName"].ToString()
                           });


                           switch ((ControlTypes)(Enum.Parse(typeof(ControlTypes), dtFieldControls.Rows[k]["Ctl_Name"].ToString())))
                           {

                               case ControlTypes.Label:
                                   tcControl2.Controls.Add(new Label()
                                   {
                                       ID = dtFieldControls.Rows[k]["Fld_Id"].ToString(),
                                       Text = dtFieldControls.Rows[k]["Fld_DispName"].ToString()
                                   });
                                   break;
                               case ControlTypes.Text:
                                   TextBox txt = new TextBox()
                                   {
                                       ID = dtFieldControls.Rows[k]["Fld_Id"].ToString(),
                                       ClientIDMode = ClientIDMode.Static,
                                       Text = ""
                                   };
                                   tcControl2.Controls.Add(txt);
                                   txt.Attributes["name"] = string.Empty;
                                   txt.Attributes["name"] = dtFieldControls.Rows[k]["Fld_Id"].ToString();
                                 
                                  
                                   if (Event != "" && Script != "" && Event != null && Script != null)
                                   {

                                   }                                  
                                   break;
                               case ControlTypes.DateTime:
                                   TextBox dttxt = new TextBox() { ID = dtFieldControls.Rows[k]["Fld_Id"].ToString(), Text = "" };
                                   tcControl2.Controls.Add(dttxt);
                                   CalendarExtender ce = new CalendarExtender()
                                   {
                                       ID = "ce" + dtFieldControls.Rows[k]["Fld_Id"].ToString(),
                                       TargetControlID = dtFieldControls.Rows[k]["Fld_Id"].ToString(),
                                       Enabled = true,
                                       Format = "dd-MM-yyyy"
                                   };
                                   tcControl2.Controls.Add(ce); 
                               
                                   break;
                               case ControlTypes.Numeric:
                                   TextBox nutxt = new TextBox() { ID = dtFieldControls.Rows[k]["Fld_Id"].ToString(), Text = "" };
                                   tcControl2.Controls.Add(nutxt);
                                   FilteredTextBoxExtender fte = new FilteredTextBoxExtender()
                                   {
                                       ID = "fte" + dtFieldControls.Rows[k]["Fld_Id"].ToString(),
                                       TargetControlID = dtFieldControls.Rows[k]["Fld_Id"].ToString(),
                                       Enabled = true,
                                       FilterType = FilterTypes.Numbers
                                   };
                                   tcControl2.Controls.Add(fte);

                                   break;
                               case ControlTypes.DropDown:

                                   TextBox txtDrop = new TextBox()
                                    {
                                        ID = dtFieldControls.Rows[k]["Fld_Id"].ToString(),
                                        ClientIDMode = ClientIDMode.Static,
                                        Text = ""
                                    };
                                   HiddenField hdnDrop = new HiddenField()
                                   {
                                       ID = "hdf" + dtFieldControls.Rows[k]["Fld_Id"].ToString(),
                                       ClientIDMode = ClientIDMode.Static,
                                       Value = ""
                                   };
                                   tcControl2.Controls.Add(txtDrop);
                                   tcControl2.Controls.Add(hdnDrop);
                                   break;
                               case ControlTypes.Button:

                                   Button btn = new Button()
                                   {
                                       ID = dtFieldControls.Rows[k]["Fld_Id"].ToString(),
                                       ClientIDMode = ClientIDMode.Static,
                                       Text = dtFieldControls.Rows[k]["Fld_DispName"].ToString()
                                   };
                                   if (Event != "" && Script != "" && Event != null && Script != null)
                                   {
                                       btn.Attributes.Add(Event, Script);
                                   }
                                   tcControl1.Controls.RemoveAt(0);
                                   tcControl2.Controls.Add(btn);
                                   break;
                           }

                           trControls.Cells.Add(tcControl1);
                           trControls.Cells.Add(tcControl2);
                           dtFieldControls.Rows.RemoveAt(k);
                           dtFieldControls.AcceptChanges();


                           k++;
                           if (k == dtFieldControls.Rows.Count)
                           {
                               k = 0;
                           }
                           else if (k == dtFieldControls.Rows.Count - 1)
                           {
                               k = 0;
                           }
                       }
                   }

                   tbControls.Rows.Add(trControls);

                   k = 0;
                   if (i >= dtFieldControls.Rows.Count)
                   {
                       i = 0;
                   }
               }
               
               TabPanel TempTab = (TabPanel)tabcEmpManage.FindControl(TabId);
               TempTab.Controls.Add(tbControls); 
              
           }
        }

        #region ActionHandler
        /// <summary>
        /// Handling control events
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ActionHandler(object sender, EventArgs e)
        {
           
            try
            {
                TabPanel Tab_EmployeeBasic = (TabPanel)tabcEmpManage.FindControl("Tab_EmployeeBasic");
                TextBox Txt_EmpName = (TextBox)Tab_EmployeeBasic.FindControl("Txt_EmpName");

                ClientScript.RegisterStartupScript(this.GetType(), "alerScript", String.Format("javascript:alert('The Textbox value is {0}')", Txt_EmpName.Text), true);
              
            }
            catch (Exception ex)
            {
               
            }
            finally
            {
                
            }
        }
        #endregion 
        // Generic method
        static public List<T> GetResults<T>(T element, ObjectContext ctx, string cmd)
        {
            // List of T elements to be returned.
            List<T> results = null;

            // Execute the query
            if (cmd == "")
            {
                results = null;
            }
            else
            {
                results = ctx.ExecuteStoreQuery<T>(cmd, null).ToList();
            }

            // Return the results
            return results;
        }

        public DataTable LINQToDataTable<T>(IEnumerable<T> varlist)
        {
             DataTable dtReturn = new DataTable();

             // column names 
             PropertyInfo[] oProps = null;

             if (varlist == null) return dtReturn;

             foreach (T rec in varlist)
             {
                  // Use reflection to get property names, to create table, Only first time, others          will follow 
                  if (oProps == null)
                  {
                       oProps = ((Type)rec.GetType()).GetProperties();
                       foreach (PropertyInfo pi in oProps)
                       {
                            Type colType = pi.PropertyType;

                            if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition()      
                            ==typeof(Nullable<>)))
                             {
                                 colType = colType.GetGenericArguments()[0];
                             }

                            dtReturn.Columns.Add(new DataColumn(pi.Name, colType));
                       }
                  }

                  DataRow dr = dtReturn.NewRow();

                  foreach (PropertyInfo pi in oProps)
                  {
                       dr[pi.Name] = pi.GetValue(rec, null) == null ?DBNull.Value :pi.GetValue
                       (rec,null);
                  }

                  dtReturn.Rows.Add(dr);
             }
     return dtReturn;
}

        enum ControlTypes
        {
            Page,
            Label,
            Text,
            DropDown,
            DateTime,
            Numeric,
            Button,
            Spacer
        }

        class Master
        {
           public  Int16 Id { get; set;}
           public string Name { get; set; }

        }


        protected override object SaveViewState()
        {
            object[] newViewState = new object[2];

            List<string> txtValues = new List<string>();

            foreach (TabPanel tp in tabcEmpManage.Controls)
            {
                foreach (Table tb in tp.Controls)
                {
                      foreach (TableRow rw in tb.Controls)
                        {
                            foreach (TableCell cl in rw.Controls)
                            {
                                if (cl.Controls.Count != 0)
                                        {
                                            if (cl.Controls[0] is DropDownList)
                                            {
                                                txtValues.Add(((DropDownList)cl.Controls[0]).SelectedIndex.ToString());
                                            }
                                            else if (cl.Controls[0] is TextBox)
                                            {
                                                txtValues.Add(((TextBox)cl.Controls[0]).Text.ToString());
                                            }
                                        }
                                    }
                                }
                            }
                        }
                      

            newViewState[0] = txtValues.ToArray();
            newViewState[1] = base.SaveViewState();
            return newViewState;
        }

        protected override void LoadViewState(object savedState)
        {
            //if we can identify the custom view state as defined in the override for SaveViewState
            var expectedType = typeof(object);
            if ( savedState.GetType()==expectedType.MakeArrayType() && ((object[])savedState).Length == 2 )
            {
                object[] newViewState = (object[])savedState;
                string[] txtValues = (string[])newViewState[0];
                if (txtValues.Length > 0)
                {
                    //re-load tables
                   
                        BindTabControls();
                        BindPageControls(tabcEmpManage.ActiveTab.ID);
                        int i = 0;
                          foreach (TabPanel tp in tabcEmpManage.Controls)
                            {
                                foreach (Table tb in tp.Controls)
                                {
                                      foreach (TableRow rw in tb.Controls)
                                        {
                                            foreach (TableCell cl in rw.Controls)
                                            {
                                                if (cl.Controls.Count != 0)
                                                        {
                                                            if (cl.Controls[0] is DropDownList && i < txtValues.Length - 1)
                                                            {
                                                                ((DropDownList)cl.Controls[0]).SelectedIndex = Convert.ToInt32(txtValues[System.Math.Max(System.Threading.Interlocked.Increment(ref i), i - 1)]);
                                                            }
                                                            else if (cl.Controls[0] is TextBox && i < txtValues.Length - 1)
                                                            {
                                                                ((TextBox)cl.Controls[0]).Text = txtValues[System.Math.Max(System.Threading.Interlocked.Increment(ref i), i - 1)].ToString();
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                  

                }
                //load the ViewState normally
                base.LoadViewState(newViewState[1]);
            }
            else
            {
                base.LoadViewState(savedState);
            }
        }

    }
}

Category:

About http://dotnetvisual.blogspot.in/:
DOT NET TO ASP.NET is a web application framework marketed by Microsoft that programmers can use to build dynamic web sites, web applications and web services. It is part of Microsoft's .NET platform and is the successor to Microsoft's Active Server Pages (ASP) technology. ASP.NET is built on the Common Language Runtime, allowing programmers to write ASP.NET code using any Microsoft .NET language. create an application very easily ....