Creating the Controls dynamically in ASP.Net

Leave a Comment
The following example will demonstrate , How to Create the Asp.Net Controls dynamically and add them to the Page.
Let us Assume a Scenario like , In One Page i have to show all the Polls from the Custom List.
Each Poll may have different count of the Options And I submit the Poll Selection Options to the Custom List.

        #region [ Page Load ]
        /// <summary>
        /// Executes when the page loads and create the controls dynamically(Poll Questions and Options)
        /// </summary>
        /// <param name="sender">Page_Load</param>
        /// <param name="e">EventArgs</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {             
                if (!IsPostBack)
                {
                    CreateConrols();
                }
            }
            catch (Exception ex)
            {
             
            }
        }
        #endregion [ Page Load ]

        #region [ Methods ]

        /// <summary>
        /// This methos is used to create the create the question and options dynamically
        /// </summary>
        public void CreateConrols()
        {
            try
            {
                // *********** assigning the parameter to the BLL Method
                objUtilities.ListName = "MyListName";
                objUtilities.Query = "";
                objUtilities.ViewFields = "<FieldRef Name='Question' /><FieldRef Name='Options' /><FieldRef Name='IsActive1' /><FieldRef Name='Option_x0020_1' /><FieldRef Name='Option_x0020_2' /><FieldRef Name='Option_x0020_3' /><FieldRef Name='Option_x0020_4' /><FieldRef Name='Option_x0020_5' /><FieldRef Name='Option_x0020_6' />";
                objUtilities.IsAll = true;
                // *********** calling a method in BLL
                dtPollsAll = new DataTable();
                dtPollsAll = objUtilities.GetDataFromSP(objUtilities);

                if (dtPollsAll != null && dtPollsAll.Rows.Count > 0)
                {
                    ViewState["vs_PollsAll"] = dtPollsAll;
                    Table table = new Table();
                    table.CssClass = "Classname for the Table";
                    TableRow tr;
                    TableCell tc;
                    //gets the count from the datatable
                    PollsCount = dtPollsAll.Rows.Count;
                    for (int i = 0; i < PollsCount; i++)
                    {
                        tr = new TableRow();
                        tc = new TableCell();

                        // Question - creating the control dynamiclly and assigning the value to it
                        Label lblDynamicQuestion = new Label();
                        lblDynamicQuestion.ID = "lbl"l + dtPollsAll.Columns["Question"].ColumnName.ToString() + i;//lbl
                        lblDynamicQuestion.Text = dtPollsAll.Rows[i][BLL.Constants.ListColumns.LstItem_Question].ToString();
                        lblDynamicQuestion.CssClass = "PollQus";

                        // ID - Poll ID - creating the id control dynamically and assigning the value to it
                        HiddenField hfDynamicID = new HiddenField();
                        hfDynamicID.ID = "hf" + dtPollsAll.Columns["ID"].ColumnName.ToString() + i;//hf
                        hfDynamicID.Value = dtPollsAll.Rows[i][BLL.Constants.ListColumns.LstItem_ID].ToString();
                      
                        // Gets the options count
                        Options = Convert.ToInt32(dtPollsAll.Rows[i]["Options"]);

                        // Options - creating the Options (radiobuttionlist) control dynamically and assigning values to it.
                        RadioButtonList rblDynamicPollOptions = new RadioButtonList();
                        rblDynamicPollOptions.ID = "rbtnL" + dtPollsAll.Columns["Options"].ColumnName.ToString() + i;//rbtnL
                        rblDynamicPollOptions.CssClass = "PollOpt";
                        // Adding Polls Options to the radio button list
                        for (int option = 0; option < Options; option++)
                        {
                            rblDynamicPollOptions.Items.Add(new ListItem(dtPollsAll.Rows[i]["Option_" + (option + 1)].ToString(), dtPollsAll.Rows[i]["Option_" + (option + 1)].ToString()));
                        }

                        // Submit  - creating the Submit(button) control dynamically and assigning the value to it.
                        Button btnDynamicSubmit = new Button();
                        btnDynamicSubmit.ID = "btnSubmit" + i;//"btnSubmit"
                        btnDynamicSubmit.Text = "Vote";
                        btnDynamicSubmit.ValidationGroup = "PollsGroup" + i;

                        // event click for button
                        btnDynamicSubmit.Click += new System.EventHandler(SubmitPoll_Click);
                        btnDynamicSubmit.CssClass = "PollVote";

                        // Creating the Required Field Validator for Polls
                        RequiredFieldValidator rfRequired = new RequiredFieldValidator();
                        rfRequired.ID = "rf" + i;//"rf"
                        rfRequired.ControlToValidate = rblDynamicPollOptions.ID;
                        rfRequired.Display = ValidatorDisplay.Dynamic;                      
                        rfRequired.ErrorMessage = "Please Select teh Poll Option";
                        rfRequired.ValidationGroup = "PollsGroup"s + i;

                        // adding controls to the tc
                        tc.Controls.Add(lblDynamicQuestion);
                        tc.Controls.Add(rblDynamicPollOptions);
                        tc.Controls.Add(btnDynamicSubmit);
                        tc.Controls.Add(hfDynamicID);
                        tc.Controls.Add(rfRequired);
                        // adding TC to the TR
                        tr.Controls.Add(tc);
                        // adding TR to the Table
                        table.Controls.Add(tr);
                    }
                    // adding table to the Panel
                    pnlMain.Controls.Add(table);
                }
                else
                {
                    //NoDataFound;
                }
            }
            catch (Exception ex)
            {
              
            }
        }

        /// <summary>
        /// this method is used to stay back the controls when the page is loading again in a page
        /// </summary>
        /// <param name="savedState"></param>
        protected override void LoadViewState(object savedState)
        {
            try
            {
                base.LoadViewState(savedState);
                CreateConrols();
            }
            catch (Exception ex)
            {
              
            }
        }

        #endregion [ Methods ]

        #region [ Events ]
        /// <summary>
        /// Executes when button clicks
        /// This Event is used to Capture the Poll Selection from the User and storing it in a PollsUserList
        /// </summary>
        /// <param name="sender">Button - SubmitPoll</param>
        /// <param name="e">EventArgs</param>
        protected void SubmitPoll_Click(object sender, EventArgs e)
        {
            try
            {
                // identify which button was clicked and perform necessary actions
                Button button = sender as Button;
                string btnId = button.ID;

                string item = btnId.Substring(9);//9 is the length of the btnSubmit ,
                               
                HiddenField ID = (HiddenField)pnlMain.FindControl("hfID" + item);// "hfID"
                RadioButtonList responce = (RadioButtonList)pnlMain.FindControl(""rbtnLOptions" + item);//"rbtnLOptions"

                if (!string.IsNullOrEmpty(ID.Value))
                    objUtilities.PollID = ID.Value;

                objUtilities.LoginUser = SPContext.Current.Web.CurrentUser.Name.ToString();

                //checking already participated or not
                if (objUtilities.isVote(objUtilities))
                {
                                     ScriptManager.RegisterStartupScript(this.Page, this.GetType(), Guid.NewGuid().ToString(), "alert('User is Already Participated in Polls')", true);
                                   }

                else
                {
                    // User Is Not Participated - assigning the selected value to the object BLL
                    if (responce != null)
                        objUtilities.Answer = responce.SelectedItem.Text;
                    // Calling a Method in BLL to store the PollNominations
                    if (objUtilities.SubmitPolls(objUtilities))
                    {
                        ScriptManager.RegisterStartupScript(this.Page, this.GetType(), Guid.NewGuid().ToString(), "alert('thank you for participating in Polls')", true);
                    }
                }
            }
            catch (Exception ex)
            {
              
            }
        }
        #endregion [ Events ]
    }
}

Related Post

0 comments:

Post a Comment