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.