As mentioned earlier, a Web Part can be developed as a user control (which is like a partial page, with markup code and a code-behind) or a custom control (which is a class written in C# for which you create the output 100% programmatically). The choice between the two depends on your needs and requirements, and it’s much like the choice between writing user and custom controls in general. If you want to compile everything into an assembly—so that the source code is protected and the output cannot be modified by an external developer and shared among multiple web sites by installing it in the GAC—then you’ll want to go with custom controls. If, instead, you don’t care much about those aspects, but prefer simplicity and speed of development, and the ease of changing the appearance of the Web Part by working with markup code instead of with C# code, then user controls will be your best bet. In this section, I’ll provide a quick overview of both approaches.
Building a Web Part as a User Control
For our first example we’ll build a simple online calculator, with two textboxes for the operands, a button to submit the form and do the calculation, and a label to show the result. You define the UI with the usual markup code, in the .ascx file (typical of user controls):
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="Calculator.ascx.cs"
Inherits=" Calculator" %>
Op1: <asp:TextBox ID="txtOp1" runat="server" /><br />
Op2: <asp:TextBox ID="txtOp2" runat="server" /><br />
<asp:Button ID="btnCalc" runat="server" Text="Calculate"
OnClick="btnCalc_Click" /><br />
<asp:Label ID="lblResult" runat="server" />
The code-behind needs a property that specifies the type of operation to perform: addition, subtraction, division, or multiplication. The property is named Operation, and is of type OperationType, an enumeration that contains the values indicated above. Then, when the button is clicked, you simply retrieve the input strings, convert them to integers, perform the specified operation, and show the result (I’m not showing the type checks and other validations in order to keep this simple):
public enum OperationType : int
{
Addition,
Subtraction,
Division,
Multiplication
}
public partial class Calculator : System.Web.UI.UserControl
{
private OperationType _operation = OperationType.Addition;
public OperationType Operation
{
get { return _operation; }
set { _operation = value; }
}
protected void btnCalc_Click(object sender, EventArgs e)
{
int op1 = Convert.ToInt32(txtOp1.Text);
int op2 = Convert.ToInt32(txtOp2.Text);
if (this.Operation == OperationType.Addition)
lblResult.Text = (op1 + op2).ToString();
else if (this.Operation == OperationType.Subtraction)
lblResult.Text = (op1 - op2).ToString();
if (this.Operation == OperationType.Division)
lblResult.Text = ((double)op1 / (double)op2).ToString();
else
lblResult.Text = (op1 * op2).ToString();
}
}
So far this is a 100% standard user control. Even so, it can be used as a Web Part on a page. Actually, any control can be used as a Web Part: ASP.NET will take care of wrapping it into a GenericWebPart at runtime. However, to enable users to personalize it by setting the properties, you need to add some attributes to the public properties that you want to make editable at runtime. In particular, the WebBrowsable attribute specifies that the property will be visible in the Web Part’s Editor box; the Personalizable attribute specifies whether the property is editable (either for the shared view or also at the user level in the personal view); the WebDisplayName specifies the property title in the editor box, so that it’s more understandable and user friendly; and the WebDescription attribute is a longer description of the property. In this example, you would decorate the Operation property with attributes as follows:
private OperationType _operation = OperationType.Addition;
[Personalizable(PersonalizationScope.User),
WebBrowsable,
WebDisplayName("Operation Type"),
WebDescription("The type of operation performed when submit is clicked.")]
public OperationType Operation
{
get { return _operation; }
set { _operation = value; }
}
Because this is just a normal user control that ASP.NET will wrap with GenericWebPart, it doesn’t specify Web Part–specific attributes such as the title that should be listed on the Web Parts catalog, or an icon. You can add those attributes to a user control by implementing the IWebPart interface, which defines properties with self-descriptive names such as Title, Description, TitleIconImageUrl, CatalogIconImage, and TitleUrl. You implement these properties as simple wrappers for private fields, as follows:
public partial class Controls_Calculator : System.Web.UI.UserControl, IWebPart
{
private string _catalogIconImageUrl = "";
public string CatalogIconImageUrl
{
get { return _catalogIconImageUrl; }
set { _catalogIconImageUrl = value; }
}
private string _description = "";
public string Description
{
get { return _description; }
set { _description = value; }
}
protected string _subTitle = "";
public string Subtitle
{
get { return _subTitle; }
set { _subTitle = value; }
}
protected string _title = "Online Calculator";
public string Title
{
get { return _title; }
set { _title = value; }
}
private string _titleIconImageUrl = "";
public string TitleIconImageUrl
{
get { return _titleIconImageUrl; }
set { _titleIconImageUrl = value; }
}
private string _titleUrl = "";
public string TitleUrl
{
get { return _titleUrl; }
set { _titleUrl = value; }
}
// ...the rest of the class as shown earlier...
}
Note that the _title field is initialized with “Online Calculator”, which is the string that will be shown in the Web Part catalog to refer to this Web Part, and on the title bar of the Web Part itself when added on the page. You’ll learn how to build and use the catalog shortly.
NOTE: This excerpt was taken from the book "ASP.NET 2.0 Website Programming". Click here to find more about it, and download the complete source code of the sample project.