Friday, December 24, 2010

Loading User Control Dynamically in ASP.NET


Hi Guys,
             
                 Recently i have got a requirement to load the user control dynamically in to a  page.When i drag and drop the user Control  in design surface run the app it is  working fine but when i load the User Control dynamically(Programmatically) .I am unable to find the Control while post back .So i have started dig the functionality and  finally i have Fixed the issue .Here is the solution .
Step#1              
                             Write the method which take user Control name as  a parameter .Call this method wherever it is required   Add the placeholder control to your page and name it as "plchUserCtrlContainer"

private void LoadUserControl(string urcName)    
          {
           string path = Server.MapPath(@"~\Controls\" + urcName + ".ascx");
           if (System.IO.File.Exists(path))
           {
               Session["FormName"] = urcName;
               Control ucMainControl = LoadControl(@"~\Controls\" + urcName + ".ascx");
               if (ucMainControl != null)
               {
                   plchUserCtrlContainer.Controls.Clear();
                   ucMainControl.ID = Session["FormName"].ToString();
                   plchUserCtrlContainer.Controls.Add(ucMainControl);
                 
               }
           }
       }



Step#2       
        Write Page OnInit event functionality as i have specified below .



override protected void OnInit(EventArgs e)
       {
       
           Session["FormName"] = Request["FormName"].ToString();
           Control ucMainControl = LoadControl(@"~\Controls\" + Session["FormName"] + ".ascx");
           plchUserCtrlContainer.Controls.Clear();
           ucMainControl.ID = Session["FormName"].ToString();
           plchUserCtrlContainer.Controls.Add(ucMainControl);

       }



Step#3       
         You  can find the control using following  line of code




protected void btnsave_Click(object sender, EventArgs e)
       {
          
               Control assControl = (Control)FindControl(Session["FormName"].ToString());
       }

Happy coding …..

2 comments:

alexmanr said...

Hi, thank you for the post, but I don´t understand how works Request["FormName"], where set it a value, from where takes it value?
Thanks in advance.

bharat said...

Thanks for the update. I think the writing was on the wall when your posts
started dropping off noticeably in the past several months, but I'm glad that
you will each continue blogging in your own forums. Best of luck to both of you
in the future, and thank you for many informative, lovely posts