Wrapping Web Controls in a SharePoint Web Part

ost of the time, creating a Web Part in SharePoint isn’t about creating a totally new user interface; instead, the task usually involves connecting existing controls with SharePoint data or with SharePoint’s toolparts so you can configure them. For example, you may want to connect a simple data grid with a SQL data source. Most of the visual interface isn’t Web Part visual interface code?it comes directly from the data grid Web control. The Web Part connects the Web control with the configuration data that the user provided.

In this article, you’ll see two basic ways of wrapping an existing Web control in a SharePoint Web Part and explore the strengths and weaknesses of each one. First, I’ll show you the Render method, and then discuss adding the control to the control tree.

Using the Render Method
Perhaps the easiest and most straightforward method for managing an underlying Web control is to do it directly?first create the control and set its properties, and then make one quick call to the RenderControl() method to get the rendered HTML for the control, and another to add that HTML to the page output. That sequence, called the Render method, lets you obtain the output generated by a Web control quickly and painlessly.

The benefit is that it’s fast and easy to trap errors, so it’s possible to detect and resolve errors relatively easily within the context of SharePoint. A quick try/catch block around the code can capture and display any errors that occur during the process.

The result is a snapshot of the control as it would render itself with no outside information. The control doesn’t have the benefit of knowing what kind of browser it was rendering for, and it doesn’t have the ability to set up event handlers. It’s just a straight HTML copy of what the control would do if you inserted it directly into the page.

One of the challenges of the Render method is that it circumvents the normal sequence of events fired for a control connected to the page?in other words, the events do not fire when you render a control through its RenderControl method. This has the nasty habit of causing third party Web controls to crash when you attempt to use them with the Render method.

The essence of the Render method is overriding the RenderWebPart method in a WebPart-derived class. Within the method, you create the underlying Web control, set the appropriate properties, and then call the RenderControl method. The following code (you can download the code) shows how.

   protected override void RenderWebPart(      HtmlTextWriter output)   {      try      {         System.Data.SqlClient.SqlConnection mySQLConnect =             new SqlConnection(connectionString);             mySQLConnect.Open();             SqlCommand myCmd = new SqlCommand(             sqlString, mySQLConnect);             System.Data.SqlClient.SqlDataAdapter myAdapter =              new SqlDataAdapter(myCmd);          DataSet ds = new DataSet();             myAdapter.Fill(ds, "Data");             DataGrid dg = new DataGrid();          dg.DataSource = ds.Tables[0];          dg.DataBind();          dg.RenderControl(output);      }      catch (Exception excpt)      {         output.Write(excpt.ToString());      }   }   

The crux of this example occurs in the last line of the try block when the code calls the RenderControl method of the DataGrid class in the line dg.RenderControl(output), passing the same HtmlTextWriter named output that the RenderWebPart method receives as an argument. This call adds the rendered version of the control to the output stream. The rest of the code sets up the DataGrid with the results of a SQL query. The variables connectionString and sqlstring are properties of the Web Part containing the connection string necessary to connect to the data source and the SQL query to fetch the data.

Adding the Control to the Tree
Sometimes, you will require a slightly more complicated approach; however, it may affect debugging. The alternative to rendering the control into the output is to add the Web control as a child control to the Web Part. This is something that Web controls do all the time?draw themselves from a series of inner controls. For example, a data grid renders as a set of label, table, and hyperlink controls arranged in a way that makes sense.

Ultimately, this process is more complicated and harder to debug. It’s more difficult to trap errors because you have less control over the way SharePoint (or more accurately, ASP.NET) draws the underlying controls. If one of the underlying Web controls being used in your Web Part throws an exception, that exception may percolate back up to SharePoint. SharePoint will respond by displaying a general-purpose error message that will do little, if anything, to help you understand what happened or where it occurred.

However, the upside is that the underlying Web control that you’re using will be connected to the page so it can determine what kind of browser the client is using, and can fire events. Many developers have tried the Render method of rendering their controls only to find that there was something missing.

For example, if the Web control you’re adding needs an event to fire that the Render method doesn’t support, such as Prerender, if it needs to be able to inspect the browser that’s calling it so it can determine how to write client-side JavaScript, or if there are events which need to fire for the control based on user input, you can find yourself out of luck?or more likely, confused as to the nature of the problem. Adding a control to the control tree avoids such negative scenarios.

Moreover, adding the control to the control tree is as easy, if not easier, than rendering the output of the control; however, there are differences. To add a control to the control tree, you make changes to the constructor of the object, as in the following AddTree method.

   public AddTree()   {      System.Data.SqlClient.SqlConnection mySQLConnect =          new SqlConnection(connectionString);      mySQLConnect.Open();      SqlCommand myCmd = new SqlCommand(sqlString,          mySQLConnect);         System.Data.SqlClient.SqlDataAdapter myAdapter = new          SqlDataAdapter(myCmd);      DataSet ds = new DataSet();         myAdapter.Fill(ds, "Data");         DataGrid dg = new DataGrid();      dg.DataSource = ds.Tables[0];      dg.DataBind();      Controls.Add(dg);   }

Note that the code in the AddTree method is not that different in structure from the code in the RenderWebPart method shown earlier. In both methods most of the code sets up the DataGrid for display, but AddTree adds the control to the control tree (by calling the Controls.Add method in the last line) rather than sending the rendered output directly as in RenderWebPart.

The other difference is that in RenderWebPart, the code is in the RenderWebPart method, which receives an HtmlTextWriter argument, whereas AddTree places the code directly in the constructor for the Web Part. In AddTree, you don’t need to call the RenderControl method because that would override .NET’s normal control processing and prevent the control from displaying. Conversely, the RenderWebPart method didn’t have a constructor for the Web Part because all its work takes place through methods.

Overriding the RenderWebPart Method
You can perform the same actions as in the above constructor in a function called as a part of your own RenderWebPart method as long as it calls the base RenderWebPart which will render the sub-control that you’ve added. An example below shows a quick and easy way to move the code for creating child controls into the RenderWebPart function.

   private bool bDGAdded = false;      protected override void RenderWebPart(      HtmlTextWriter output)   {      // If the data grid has not been added      if (!bDGAdded) AddDG();         base.RenderWebPart(output);   }      protected void AddDG()   {      System.Data.SqlClient.SqlConnection mySQLConnect = new          SqlConnection(connectionString);         mySQLConnect.Open();         SqlCommand myCmd = new SqlCommand(sqlString,          mySQLConnect);         System.Data.SqlClient.SqlDataAdapter myAdapter = new          SqlDataAdapter(myCmd);      DataSet ds = new DataSet();         myAdapter.Fill(ds, "Test");         DataGrid dg = new DataGrid();      dg.DataSource = ds.Tables[0];      dg.DataBind();      Controls.Add(dg);      bDGAdded = true;

}

A Simple Example
It’s worth looking at the two different Web Parts as they are displayed in the portal. After you’ve compiled and added the Web controls to your portal or site, you’ll be confronted with some trapped errors. The first error indicates that the connection string is null. To fix that, select Modify Shared Web Part from the Web Part drop-down menu. Scroll down to the bottom and expand the data section. In the connection box enter a connection string such as the following:

   Server=localhost;database=pubs;Integrated       Security=false;User Id=sa;Password=myPassword

Obviously, you’ll need to replace the username and password in this connection string with valid User Id and Password values for your environment.

After entering the connection string, scroll down and enter a SQL query into the SQL Command box. For example, you might enter:

   SELECT TOP 2 au_lname, au_fname FROM Authors

When you click OK the Web Part will display the first two rows from the Authors table from the pubs sample database.

If you follow the same process with the other Web Part you’ll see that both Web Parts display the same output. With a simple example such as a data grid without any special formatting or click-through events they will be the same. The difference is that the Render method won’t support the callback events you’ll likely want to use to make a complete solution.

Although you’ll find that it’s more common to use the Render method to wrap Web controls, that’s often not the correct choice when you’re wrapping complicated Web controls. In those cases, it may be better to add the Web control to the Web Part’s control tree so it can manage its own rendering as it was designed to work.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

The Latest

your company's audio

4 Areas of Your Company Where Your Audio Really Matters

Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a

chrome os developer mode

How to Turn on Chrome OS Developer Mode

Google’s Chrome OS is a popular operating system that is widely used on Chromebooks and other devices. While it is designed to be simple and user-friendly, there are times when users may want to access additional features and functionality. One way to do this is by turning on Chrome OS

homes in the real estate industry

Exploring the Latest Tech Trends Impacting the Real Estate Industry

The real estate industry is changing thanks to the newest technological advancements. These new developments — from blockchain and AI to virtual reality and 3D printing — are poised to change how we buy and sell homes. Real estate brokers, buyers, sellers, wholesale real estate professionals, fix and flippers, and beyond may