1

i have a really simple question and probably hard answer.
i want to add webpartzone into my sharepoint page using c# code, how can i do that?
i search all of web and found nothing.
what i did is: i create visual web part project and added this code to page_init event of it:

protected void Page_Init(object sender, EventArgs e)
{
    WebPartZone webPartZone1 = new WebPartZone();
    webPartZone1.AllowLayoutChange = true;
    webPartZone1.EmptyZoneText = "No Data are provided";
    webPartZone1.Enabled = true;
    webPartZone1.HeaderText = "My Custom Zone";
    webPartZone1.Visible = true;

    this.Page.Controls.Add(webPartZone1);
}  

and it's doesn't work. but can give you some idea of what i want. im really confused. could anyone help. thanks anyway.

2
  • This is a little old to still not have a definite answer ...
    – SpYk3HH
    Commented Oct 11, 2012 at 20:50
  • actually i give it up because it have some logical issue i think. as i said in Laurie's comments. Commented Oct 13, 2012 at 20:38

2 Answers 2

1

Try adding your web part zone into the controls collection of a TD on your page instead of directly to the page. Also, make sure you give your new webpartzone an ID.

Your page markup:

<table>
  <tr>
    <td id="TopLeftZone" runat="server"></td>
  </tr>
</table>

Your code-behind:

WebPartZone webPartZone1 = new WebPartZone();
webPartZone1.ID = "myTopLeftZone";
. . .
TopLeftZone.Controls.Add(webPartZone1);
3
  • 1
    thanks for replay. i try this but i got error, because how can i add the webpartzone with webpart. i think my solution is a mistake. Commented Jul 17, 2011 at 13:38
  • Are you saying you got an error when you add your webpart to the page? And, do you mean you are going to solve your problem in another way? If you can add your webpartzone to the aspx page in the markup instead of using C#, that would certainly be a good solution.
    – Laurie
    Commented Jul 17, 2011 at 20:17
  • 1
    I'm saying that because when you wanna add your webpart in page you have to add to webpartzone that you selected in combobox and how can you add webpartzone in another one since webpart itself is in another webpartzone that selected?! but thanks for the time you spend. Commented Jul 19, 2011 at 5:27
0

I think you will have to update the aspx file content directly (adding the webpart zone template tag).

Using the code you wrote, you won't persist the control addition

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.