Custom Controls
From Section 6.6.2 of the book
This is an example of a Custom Control that can be used to fold away
text parts in web pages and to replace them with background text parts.
The control is implemented as a class Fold, which is derived
from the class ImageButton:
Fold.cs
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
namespace Folds {
[ParseChildren(false)]
public class Fold : ImageButton {
public event EventHandler FileNotFound;
public string Text {
get { return ViewState["Text"]==null ? "" : (string)ViewState["Text"]; }
set { ViewState["Text"] = value; }
}
public string Icon {
get { return ViewState["Icon"]==null ? "Solid" : (string)ViewState["Icon"]; }
set { ViewState["Icon"] = value; }
}
public Fold() : base() {
Click += new ImageClickEventHandler(FoldClick);
}
protected override void AddParsedSubObject(object obj) {
if (obj is LiteralControl) AlternateText = ((LiteralControl)obj).Text;
}
void FoldClick(object sender, ImageClickEventArgs e) {
string s = Text;
Text = AlternateText;
AlternateText = s;
if (Icon == "Solid") Icon = "Hollow"; else Icon = "Solid";
}
protected virtual void OnFileNotFound(EventArgs e) {
if (FileNotFound != null) FileNotFound(this, e);
}
protected override void OnClick(ImageClickEventArgs e) {
try {
if (AlternateText.StartsWith("@")) {
string fileName = Page.MapPath(TemplateSourceDirectory)
+ "/" + AlternateText.Substring(1);
FileStream s = File.OpenRead(fileName);
StreamReader r = new StreamReader(s);
AlternateText = r.ReadToEnd();
}
} catch (FileNotFoundException) {
OnFileNotFound(EventArgs.Empty);
} finally {
base.OnClick(e);
}
}
protected override void Render(HtmlTextWriter w) {
w.Write("<" + "input type=image name=" + this.UniqueID);
w.Write(" src='" + TemplateSourceDirectory + "/" + Icon + "Left.gif' border=0 />");
w.Write(Text);
w.Write("<" + "img src='" + TemplateSourceDirectory + "/" + Icon + "Right.gif'>");
}
}
}
|
This class must be compiled into a DLL which must be stored in a subdirectory
/bin under the virtual directory. The compilation command looks like this:
csc /target:library /out:bin/Folds.dll Fold.cs
Now the Custom Control can be used in an aspx page.
Fold.aspx
<%@ Page Language="C#" %>
<%@ Register TagPrefix="my" Namespace="Folds" Assembly="Folds" %>
<html>
<body>
<form Runat="server">
<my:Fold Text="Please read!" Runat="server">
ASP.NET allows the development of custom controls
that open up almost unlimited possibilities for
new web functionality.
</my:Fold>
</form>
</body>
</html>
|
Try it
http://dotnet.jku.at/book/samples/6/Fold.aspx
|