Wrapping Web Controls in a SharePoint Web Part

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.

devx-admin

devx-admin

Share the Post:
5G Innovations

GPU-Accelerated 5G in Japan

NTT DOCOMO, a global telecommunications giant, is set to break new ground in the industry as it prepares to launch a GPU-accelerated 5G network in

AI Ethics

AI Journalism: Balancing Integrity and Innovation

An op-ed, produced using Microsoft’s Bing Chat AI software, recently appeared in the St. Louis Post-Dispatch, discussing the potential concerns surrounding the employment of artificial

Savings Extravaganza

Big Deal Days Extravaganza

The highly awaited Big Deal Days event for October 2023 is nearly here, scheduled for the 10th and 11th. Similar to the previous year, this

5G Innovations

GPU-Accelerated 5G in Japan

NTT DOCOMO, a global telecommunications giant, is set to break new ground in the industry as it prepares to launch a GPU-accelerated 5G network in Japan. This innovative approach will

AI Ethics

AI Journalism: Balancing Integrity and Innovation

An op-ed, produced using Microsoft’s Bing Chat AI software, recently appeared in the St. Louis Post-Dispatch, discussing the potential concerns surrounding the employment of artificial intelligence (AI) in journalism. These

Savings Extravaganza

Big Deal Days Extravaganza

The highly awaited Big Deal Days event for October 2023 is nearly here, scheduled for the 10th and 11th. Similar to the previous year, this autumn sale has already created

Cisco Splunk Deal

Cisco Splunk Deal Sparks Tech Acquisition Frenzy

Cisco’s recent massive purchase of Splunk, an AI-powered cybersecurity firm, for $28 billion signals a potential boost in tech deals after a year of subdued mergers and acquisitions in the

Iran Drone Expansion

Iran’s Jet-Propelled Drone Reshapes Power Balance

Iran has recently unveiled a jet-propelled variant of its Shahed series drone, marking a significant advancement in the nation’s drone technology. The new drone is poised to reshape the regional

Solar Geoengineering

Did the Overshoot Commission Shoot Down Geoengineering?

The Overshoot Commission has recently released a comprehensive report that discusses the controversial topic of Solar Geoengineering, also known as Solar Radiation Modification (SRM). The Commission’s primary objective is to

Remote Learning

Revolutionizing Remote Learning for Success

School districts are preparing to reveal a substantial technological upgrade designed to significantly improve remote learning experiences for both educators and students amid the ongoing pandemic. This major investment, which

Revolutionary SABERS Transforming

SABERS Batteries Transforming Industries

Scientists John Connell and Yi Lin from NASA’s Solid-state Architecture Batteries for Enhanced Rechargeability and Safety (SABERS) project are working on experimental solid-state battery packs that could dramatically change the

Build a Website

How Much Does It Cost to Build a Website?

Are you wondering how much it costs to build a website? The approximated cost is based on several factors, including which add-ons and platforms you choose. For example, a self-hosted

Battery Investments

Battery Startups Attract Billion-Dollar Investments

In recent times, battery startups have experienced a significant boost in investments, with three businesses obtaining over $1 billion in funding within the last month. French company Verkor amassed $2.1

Copilot Revolution

Microsoft Copilot: A Suit of AI Features

Microsoft’s latest offering, Microsoft Copilot, aims to revolutionize the way we interact with technology. By integrating various AI capabilities, this all-in-one tool provides users with an improved experience that not

AI Girlfriend Craze

AI Girlfriend Craze Threatens Relationships

The surge in virtual AI girlfriends’ popularity is playing a role in the escalating issue of loneliness among young males, and this could have serious repercussions for America’s future. A

AIOps Innovations

Senser is Changing AIOps

Senser, an AIOps platform based in Tel Aviv, has introduced its groundbreaking AI-powered observability solution to support developers and operations teams in promptly pinpointing the root causes of service disruptions

Bebop Charging Stations

Check Out The New Bebob Battery Charging Stations

Bebob has introduced new 4- and 8-channel battery charging stations primarily aimed at rental companies, providing a convenient solution for clients with a large quantity of batteries. These wall-mountable and

Malyasian Networks

Malaysia’s Dual 5G Network Growth

On Wednesday, Malaysia’s Prime Minister Anwar Ibrahim announced the country’s plan to implement a dual 5G network strategy. This move is designed to achieve a more equitable incorporation of both

Advanced Drones Race

Pentagon’s Bold Race for Advanced Drones

The Pentagon has recently unveiled its ambitious strategy to acquire thousands of sophisticated drones within the next two years. This decision comes in response to Russia’s rapid utilization of airborne

Important Updates

You Need to See the New Microsoft Updates

Microsoft has recently announced a series of new features and updates across their applications, including Outlook, Microsoft Teams, and SharePoint. These new developments are centered around improving user experience, streamlining

Price Wars

Inside Hyundai and Kia’s Price Wars

South Korean automakers Hyundai and Kia are cutting the prices on a number of their electric vehicles (EVs) in response to growing price competition within the South Korean market. Many

Solar Frenzy Surprises

Solar Subsidy in Germany Causes Frenzy

In a shocking turn of events, the German national KfW bank was forced to discontinue its home solar power subsidy program for charging electric vehicles (EVs) after just one day,

Electric Spare

Electric Cars Ditch Spare Tires for Efficiency

Ira Newlander from West Los Angeles is thinking about trading in his old Ford Explorer for a contemporary hybrid or electric vehicle. However, he has observed that the majority of

Solar Geoengineering Impacts

Unraveling Solar Geoengineering’s Hidden Impacts

As we continue to face the repercussions of climate change, scientists and experts seek innovative ways to mitigate its impacts. Solar geoengineering (SG), a technique involving the distribution of aerosols

Razer Discount

Unbelievable Razer Blade 17 Discount

On September 24, 2023, it was reported that Razer, a popular brand in the premium gaming laptop industry, is offering an exceptional deal on their Razer Blade 17 model. Typically

Innovation Ignition

New Fintech Innovation Ignites Change

The fintech sector continues to attract substantial interest, as demonstrated by a dedicated fintech stage at a recent event featuring panel discussions and informal conversations with industry professionals. The gathering,

Import Easing

Easing Import Rules for Big Tech

India has chosen to ease its proposed restrictions on imports of laptops, tablets, and other IT hardware, allowing manufacturers like Apple Inc., HP Inc., and Dell Technologies Inc. more time