15.02.2015 Views

C# 4 and .NET 4

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

1194 ❘ ChaPTer 41 Asp.net feAtures<br />

Note that this property isn’t as simple as just storing a value in a member field. This is due to the way<br />

ASP.<strong>NET</strong> maintains state, as discussed in the previous chapter. Controls are instantiated on each postback<br />

operation, so to store values you must make use of view state. This is easy to access — you simply use the<br />

ViewState collection, which can store any object that is serializable. Otherwise, offset would revert to its<br />

initial value between each postback.<br />

To modify offset, you use a method called Cycle():<br />

public void Cycle()<br />

{<br />

offset = ++offset;<br />

}<br />

This simply increments the value stored in the view state for offset.<br />

Finally, you come to perhaps the most important method override for any custom control — Render(). This<br />

is where you output HTML, <strong>and</strong> as such it can be a very complicated method to implement. If you were<br />

to take into account all the browsers that may view your controls, <strong>and</strong> all the variables that could affect<br />

rendering, this method could get very big. Fortunately, for this example, it’s quite simple:<br />

}<br />

}<br />

protected override void Render(HtmlTextWriter output)<br />

{<br />

string text = Text;<br />

for (int pos = 0; pos < text.Length; pos++)<br />

{<br />

int rgb = colors[(pos + offset) % colors.Length].ToArgb()<br />

& 0xFFFFFF;<br />

output.Write(string.Format(<br />

"{1}", rgb, text[pos]));<br />

}<br />

}<br />

This method gives you access to the output stream to display your control content. There are only two cases<br />

where you don’t need to implement this method:<br />

➤<br />

➤<br />

When you are designing a control that has no visual representation (usually known as a component)<br />

When you are deriving from an existing control <strong>and</strong> don’t need to change its display characteristics<br />

Custom controls can also expose custom methods, raise custom events, <strong>and</strong> respond to child controls (if<br />

any). In the case of RainbowLabel, you don’t have to worry about any of this.<br />

Next, you need to add a web page, Default.aspx, <strong>and</strong> add code to view the control <strong>and</strong> provide access to<br />

Cycle(), as follows:<br />

<br />

...<br />

<br />

<br />

<br />

<br />

<br />

<br />

The required code in Default.aspx.cs is simply this:<br />

code snippet PCSCustomCWebSite1/Default.aspx<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!