Top Banner
User Controls & Dynamic Graphics What are user controls Types of User Controls Creating User Controls Defining Properties in User Controls Adding a User Control to a Page Defining User Control Events Passing Information with Events Dynamic Graphics
27
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Chapter 11

User Controls & Dynamic Graphics

• What are user controls

• Types of User Controls

• Creating User Controls

• Defining Properties in User Controls

• Adding a User Control to a Page

• Defining User Control Events

• Passing Information with Events

• Dynamic Graphics

Page 2: Chapter 11

User Controls

A user control is a file that you create that contains other ASP.NET controls and code grouped together to provide common functionality.

The user control can then be used on different pages within a Web Site.

User Contols are created as .ascx file. An .ascx file is similar to the .aspx file and can have its own code behind page.

Page 3: Chapter 11

User Controls

To enable reuse the .ascx and .cs file must be included in each project that requires the user control. For this reason, user controls are typically reserved for reuse within a given site. If you need reuse between sites, you should consider using Web Server Controls

Page 4: Chapter 11

Web Controls Vs. User Controls

The .ascx file for a user control begins with a <%@ Control %> directive instead ofa <%@ Page %> directive.

Their code-behind files inherit from the System.Web.UI.UserControl class

User controls can’t be requested directly by a web browser. Instead, they must beembedded inside other web pages

Page 5: Chapter 11

Types of User Controls

Conceptually, two types of user controls exist:

• Independent • Integrated

Independent user controls don’t interact with the rest of the code on your form

Integrated user controls can be very useful for breaking down a large application into smaller, more manageable chunks you integrate these user controls to a page / form to develop a feature. Integrated user controls interact in one way or another with the web page that hosts them.

Page 6: Chapter 11

Hyperlink User Control

<%@ Control Language="C#" AutoEventWireup="true"CodeFile=“HyperlinkControl.ascx.cs" Inherits=“HyperlinkControl" %><div>Products:<br /><asp:HyperLink id="lnkBooks" runat="server"NavigateUrl="MenuHost.aspx?product=Books">Books</asp:HyperLink><br /><asp:HyperLink id="lnkToys" runat="server"NavigateUrl="MenuHost.aspx?product=Toys">Toys</asp:HyperLink><br /><asp:HyperLink id="lnkSports" runat="server"NavigateUrl="MenuHost.aspx?product=Sports">Sports</asp:HyperLink><br /><asp:HyperLink id="lnkFurniture" runat="server"NavigateUrl="MenuHost.aspx?product=Furniture">Furniture</asp:HyperLink></div>

User Control File HyperlinkControl.ascx

Page 7: Chapter 11

<%@ Page Language="C#" AutoEventWireup="true » CodeFile="MenuHost.aspx.cs" Inherits="MenuHost"%><%@ Register TagPrefix="apress" TagName=“HyperlinkControl" Src=“HyperlinkControl.ascx" %><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"><title>Menu Host</title></head><body><form id="form1" runat="server"><div>

<table><tr><td><apress:HyperlinkControl id="Menu1" runat="server" /></td><td><asp:Label id="lblSelection" runat="server" /></td></tr></table>

</div></form></body></html>

Web Page MenuHost.aspx

Page 8: Chapter 11

protected void Page_Load(Object sender, EventArgs e){if (Request.Params["product"] != null){lblSelection.Text = "You chose: ";lblSelection.Text += Request.Params["product"];}}

Code Behind MenuHost.aspx.cs

Page 9: Chapter 11

An ordinary HyperLink control that doesn’t have any associated server-side code because the HyperLink control doesn’t fire an event when the link is clicked.

Instead, you’ll need to use the LinkButton. The LinkButton fires the Click event, which the LinkMenuControl can intercept, and then raises the LinkClicked event to the web page.

Every page in the website can then include the same LinkMenu user control, enabling painless website navigation with no need to worry about frames.

This LinkMenu user control can handle the events for all the buttons and then run the appropriate Response.Redirect() code to move to another web page.

Switching Over to LinkMenuControl

Page 10: Chapter 11

In the following example, you’ll see a version of the LinkMenu Control that uses events. Instead of navigating directly to the appropriate page when the user clicks a button, the control raises an event, which the web page can choose to handle.

User Control Events

public partial class LinkMenuControl : System.Web.UI.UserControl{public event EventHandler LinkClicked;...}

protected void lnk_Click(object sender, EventArgs e){ ... }

LinkClicked(this, EventArgs.Empty);

// Raising the LinkClicked event

// Declaring the LinkClicked event

// Defining the LinkClicked event

Page 11: Chapter 11

<%@ Control Language="C#" AutoEventWireup="true"CodeFile="LinkMenuControl.ascx.cs" Inherits="LinkMenuControl" %>

<div><asp:LinkButton ID="lnkBooks" runat="server" OnClick="lnk_Click">Books</asp:LinkButton><br />

<asp:LinkButton ID="lnkToys" runat="server" OnClick="lnk_Click">Toys</asp:LinkButton><br />

<asp:LinkButton ID="lnkSports" runat="server" OnClick="lnk_Click">Sports</asp:LinkButton><br />

<asp:LinkButton ID="lnkFurniture" runat="server" OnClick="lnk_Click">Furniture</asp:LinkButton>

</div>

User Control File LinkMenuControl.ascx

LinkMenu User Control

Page 12: Chapter 11

public partial class LinkMenuControl : System.Web.UI.UserControl{public event EventHandler LinkClicked;

protected void lnk_Click(object sender, EventArgs e){// One of the LinkButton controls has been clicked.// Raise an event to the page.if (LinkClicked != null){LinkClicked(this, EventArgs.Empty);}}}

Code Behind File LinkMenuControl.ascx.cs

Page 13: Chapter 11

<%@ Page Language="C#" AutoEventWireup="true » CodeFile=“LinkMenuHost.aspx.cs" Inherits=“LinkMenuHost"%><%@ Register TagPrefix="apress" TagName="LinkMenuControl" Src="LinkMenu.ascx" %>

<html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"><body>...<apress:LinkMenuControl id="Menu1" runat="server" OnLinkClicked="LinkClicked" />...</body></html>

Web Page LinkMenuHost.aspx

Page 14: Chapter 11

protected void LinkClicked(object sender, EventArgs e){lblClick.Text = "Click detected.";}

Code Behind LinkMenuHost.aspx.cs

Page 15: Chapter 11

In the current LinkMenu example, no custom information is passed along with the event. When the LinkClicked event occurs, the web page has no way of knowing what link was clicked.

The trick is to switch from the LinkButton.Click event to the LinkButton.Command event. The Command event automatically gets the CommandArgument that’s defined in the tag.

Passing Information with Events

Page 16: Chapter 11

Also to convey additional information that relates to the event, you need to create a custom class that derives from EventArgs.

The .NET standard for events specifies that every event should use two parameters. The first one provides a reference to the control that sent the event, while the second incorporates any additional information. This additional information is wrapped into a custom EventArgs object, which inherits from the System.EventArgs class

The LinkClickedEventArgs class that follows allows the LinkMenu user control to pass the URL that the user selected through a Url property. It also provides a Cancel property. If set to true, the user control will stop its processing immediately. But if Cancel remains false (the default), the user control will send the user to the new page.

Passing Information with Events

Page 17: Chapter 11

public class LinkClickedEventArgs : EventArgs{public string Url {get; set;}public bool Cancel {get; set;}public LinkClickedEventArgs(string url){Url = url;}}

Passing Information with Events

Page 18: Chapter 11

To use this custom EventArgs class, you need to modify the definition of the LinkClicked event so it uses the LinkClickedEventArgs object:

// Declaring the LinkClicked eventpublic event EventHandler<LinkClickedEventArgs> LinkClicked;

// Defining the LinkClicked eventLinkClickedEventArgs args = new LinkClickedEventArgs((string)e.CommandArgument);

// Raising the LinkClicked eventLinkClicked(this, args);

Passing Information with Events

Page 19: Chapter 11

<asp:LinkButton ID="lnkBooks" runat="server"CommandArgument="Menu2Host.aspx?product=Books" OnCommand="lnk_Command">Books</asp:LinkButton><br /><asp:LinkButton ID="lnkToys" runat="server"CommandArgument="Menu2Host.aspx?product=Toys" OnCommand="lnk_Command">Toys</asp:LinkButton><br /><asp:LinkButton ID="lnkSports" runat="server"CommandArgument="Menu2Host.aspx?product=Sports" OnCommand="lnk_Command">Sports</asp:LinkButton><br /><asp:LinkButton ID="lnkFurniture" runat="server"CommandArgument="Menu2Host.aspx?product=Furniture" OnCommand="lnk_Command">Furniture</asp:LinkButton>

User Control File LinkMenuControl1.ascx

LinkMenuControl with Passed Information

Page 20: Chapter 11

public partial class LinkMenuControl1 : System.Web.UI.UserControl{public event EventHandler<LinkClickedEventArgs> LinkClicked;protected void lnk_Command(object sender, CommandEventArgs e){

if (LinkClicked != null){

// Pass along the link information.LinkClickedEventArgs args =new LinkClickedEventArgs((string)e.CommandArgument);

LinkClicked(this, args);if (!args.Cancel){Response.Redirect(args.Url);}}

Code Behind File LinkMenuControl.ascx.cs

Page 21: Chapter 11

<%@ Page Language="C#" AutoEventWireup="true » CodeFile=“LinkMenuHost.aspx.cs" Inherits=“LinkMenuHost"%><%@ Register TagPrefix="apress" TagName="LinkMenuControl" Src="LinkMenu.ascx" %>

<html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"><body>...<apress:LinkMenuControl1 id="Menu1" runat="server" OnLinkClicked="LinkClicked" />...</body></html>

Web Page LinkMenuHost.aspx

Page 22: Chapter 11

protected void LinkClicked(object sender, LinkClickedEventArgs e){if (e.Url == "Menu2Host.aspx?product=Furniture"){lblClick.Text = "This link is not allowed.";e.Cancel = true;}else{Response.Redirect(e.Url);}} protected void Page_Load(object sender, EventArgs e) { if (Request.Params["product"] != null) { lblSelection.Text = "You chose: "; lblSelection.Text += Request.Params["product"]; } }

Code Behind LinkMenuHost.aspx.cs

Page 23: Chapter 11

Basic Drawing StepsOne of the features of the .NET Framework is GDI+, a set of classes designed for drawing images.

You need to follow four basic steps when using GDI+.

• First, you have to create an in-memory bitmap.

• To create the bitmap, declare a new instance of the System.Drawing.Bitmap class.

• You must specify the height and width of the image in• pixels.

• The next step is to create a GDI+ graphics context for the image, which is represented by a System.Drawing.Graphics object.

• To create a Graphics object from an existing Bitmap object, you just use the static Graphics.FromImage() method,

Page 24: Chapter 11

Basic Drawing Steps

• Now use the methods of the Graphics class. The methods that begin with the word Draw draw outlines, while the methods that begin with the word Fill draw solid regions

• When calling the Graphics class methods, you need to specify several parameters to indicate the pixel coordinates for what you want to draw.

• You need to specify either a Brush or a Pen object when you draw most content. (Both of these classes are defined in the System.Drawing namespace, alongside the Graphics class.)

• Once the image is complete, you can send it to the browser using the Image.Save() method.

• Finally, you should explicitly release your image and graphics context when you’re finished, because both hold onto some unmanaged resources that might not be released right away if you don’t

Page 25: Chapter 11

protected void Page_Load(Object sender, EventArgs e){Bitmap image = new Bitmap(300, 50);

Graphics g = Graphics.FromImage(image);

g.FillRectangle(Brushes.LightYellow, 0, 0, 300, 50);g.DrawRectangle(Pens.Red, 0, 0, 299, 49);

Font font = new Font("Alba Super", 20, FontStyle.Regular);g.DrawString("This is a test.", font, Brushes.Blue, 10, 0);

System.Drawing.Image icon = Image.FromFile(Server.MapPath("smiley.gif"));g.DrawImageUnscaled(icon, 240, 0);

image.Save(Response.OutputStream,System.Drawing.Imaging.ImageFormat.Gif);

g.Dispose();image.Dispose();}

Dynamic Graphics Example

Page 26: Chapter 11

Placing Custom Images Inside Web Pages

The Image.Save() approach demonstrated so far has one problem. When you save an image to the response stream, you overwrite whatever information ASP.NET would other wise use.

If you have a web page that includes other content and controls, this content won’t appear at all in the final web page. Instead, the dynamically rendered graphics replace it.

Fortunately, this has a simple solution: you can link to a dynamically generated image using the <img> tag or the Image web control. But instead of linking your image to a fixed image file, link it to the .aspx file that generates the picture.

Page 27: Chapter 11

Placing Custom Images Inside Web Pages

The full Image.ImageUrl thus becomesGraphicalText.aspx?Name=Joe%20Brown, as shown here:

<asp:Image id="Image1" runat="server"ImageUrl="GraphicalText.aspx?Name=Joe%20Brown"></asp:Image>

string name = Request.QueryString["Name"];

g.DrawString(name, font, Brushes.Blue, 10, 0);