quarta-feira, 20 de maio de 2009

Creating Complex Web Parts in Sharepoint 2007 using Web User Control

My task this few days was to research on how to create comple Web Parts in Sharepoint 2007. Ideally, I create my web parts using code-behind code. In other words, I create the controls dynamically. This was gruesome in my part, because from positioning to event-handlers may take a lot of time, debugging, and most specially in designing. Take a look at my sample code I used to design a very simple web part:



protected override void CreateChildControls()
{
base.CreateChildControls();

// TODO: add custom rendering code here.

Button myButton = new Button();
myButton.Text = "Click";
myButton.Width = 50;
myButton.Height = 50;

myButton.Click += new EventHandler(myButton_Click);

this.Controls.Add(myButton);

}

void myButton_Click(object sender, EventArgs e)
{
//throw new Exception("The method or operation is not implemented.");
myLabelPublic = new Label();
myLabelPublic.Text = "For testing only. For testing only. For testing only.";
this.Controls.Add(myLabelPublic);

}

Basically, this code generate a button on it's page load. After the load, if user clicks the button, obviously, a new Label will generate displaying the message. This is not the way I want to develop my Web Parts, because it takes a lot of time.

So after a long time research, I found another way to create not just simple but you can make it complex using Web User Control. I did suspect Web User Control at the first place but I don't know how to figure it out. Anyway, here are the steps:

1.) First, of course, create your Web User Control. You have the option on how you create it, but in my part, I create it using ASP.NET 2.0 IDE. What I usually did is I create a blank page, then I add a new item which is Web User Control. Take note to uncheck the option which separate your code in a separate file.

2.) Second, design your Web User Control (ascx), from its physical design to its logic coding.

3.) Copy your ascx file to this directory: C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\CONTROLTEMPLATES

4.) Then use this sample code as your reference for adding your Web User Control file in your .cs file:



protected override void CreateChildControls()
{
base.CreateChildControls();

// TODO: add custom rendering code here.

this.Controls.Clear();
userControl = (UserControl)this.Page.LoadControl(@"/_controltemplates/Test.ascx");
this.Controls.Add(userControl);
}


protected override void RenderContents(HtmlTextWriter writer)
{
//base.RenderContents(writer);
userControl.RenderControl(writer);
}


5.) Last build then deploy your site. Make sure your output is the URL of your sharepoint site for successful deployment of your Web Part.

Um comentário:

  1. Hi,Also for the background it is best to use a light colour and on it a dark text in Web Design Cochin, preferably black text on a white background.Thanks....

    ResponderExcluir