Adde User Control in Web Part Dynamically


This Code Snippets is use for dynamically create user control and add that user control in web parts. At run time set the value to the user control. The function is use for creating user control by passing number of user control we have to create.

The function to dynamically create web part.

Here i have use
int cnt is number of web part we have to create
The followin function is user to create the web part dynamically



public void CreateDynamicWebPart (int cnt)
{
WebPartManager wpm = (WebPartManager)WebPartManager.GetCurrentWebPartManager(this.Page);

for (int i = 0; i < cnt; i++)
{

UserControl uc = (UserControl)LoadControl("~/Includes/UserControl.ascx");
//create the web part
//create the web part using CreateWebPart method
GenericWebPart gwp = wpm.CreateWebPart(uc);
//usg GenericWebPart instance for set title in web part
gwp.Title = "Web part"+ i;
Control UserCont = wpm.AddWebPart(gwp, Zone1, 1).Controls[0];
// set the value of the hidden field.
HiddenField hidenID = (HiddenField)UserCont.FindControl("hidenResourceID");
hidenID .Value = Convert.ToString(i);

}
}


Above function is use to crete the user control dynamically and add it into the web part.


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: