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 timedraw 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
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
System.Data.SqlClient.SqlConnection mySQLConnect =
SqlCommand myCmd = new SqlCommand(sqlString,
System.Data.SqlClient.SqlDataAdapter myAdapter = new
DataSet ds = new DataSet();
DataGrid dg = new DataGrid();
dg.DataSource = ds.Tables;
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.