Chapter 11


Published on

User Controls and Graphics

Published in: Technology
  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Chapter 11

  1. 1. • 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
  2. 2. A user control is a file that you create thatcontains other ASP.NET controls and codegrouped together to provide commonfunctionality.The user control can then be used ondifferent pages within a Web Site.User Contols are created as .ascx file. An.ascx file is similar to the .aspx file and canhave its own code behind page.
  3. 3. To enable reuse the .ascx and .cs file mustbe included in each project that requires theuser control. For this reason, user controlsare typically reserved for reuse within a givensite. If you need reuse between sites, youshould consider using Web Server Controls
  4. 4. The .ascx file for a user control begins with a<%@ Control %> directive instead ofa <%@ Page %> directive.Their code-behind files inherit from theSystem.Web.UI.UserControl classUser controls can’t be requested directly by aweb browser. Instead, they must beembedded inside other web pages
  5. 5. Conceptually, two types of user controls exist:• Independent• IntegratedIndependent user controls don’t interact with the rest ofthe code on your formIntegrated user controls can be very useful for breakingdown a large application into smaller, more manageablechunks you integrate these user controls to a page / formto develop a feature. Integrated user controls interact inone way or another with the web page that hosts them.
  6. 6. User Control File HyperlinkControl.ascx<%@ 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>
  7. 7. Web Page MenuHost.aspx<%@ Page Language="C#" AutoEventWireup="true »CodeFile="MenuHost.aspx.cs" Inherits="MenuHost"%><%@ Register TagPrefix="apress" TagName=“HyperlinkControl"Src=“HyperlinkControl.ascx" %><html xmlns=""><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>
  8. 8. Code Behind MenuHost.aspx.csprotected void Page_Load(Object sender, EventArgs e){if (Request.Params["product"] != null){lblSelection.Text = "You chose: ";lblSelection.Text += Request.Params["product"];}}
  9. 9. An ordinary HyperLink control that doesn’t have any associatedserver-side code because the HyperLink control doesn’t fire anevent when the link is clicked.Instead, you’ll need to use the LinkButton. The LinkButton firesthe Click event, which the LinkMenuControl can intercept, andthen raises the LinkClicked event to the web page.Every page in the website can then include the same LinkMenuuser control, enabling painless website navigation with no needto worry about frames.This LinkMenu user control can handle the events for all thebuttons and then run the appropriate Response.Redirect() codeto move to another web page.
  10. 10. In the following example, you’ll see a version of the LinkMenuControl that uses events. Instead of navigating directly to theappropriate page when the user clicks a button, the controlraises an event, which the web page can choose to handle. // Declaring the LinkClicked eventpublic partial class LinkMenuControl : System.Web.UI.UserControl{public event EventHandler LinkClicked;...} // Defining the LinkClicked eventprotected void lnk_Click(object sender, EventArgs e){ ... }// Raising the LinkClicked eventLinkClicked(this, EventArgs.Empty);
  11. 11. User Control File LinkMenuControl.ascx<%@ 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>
  12. 12. Code Behind File LinkMenuControl.ascx.cspublic 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);}}}
  13. 13. Web Page LinkMenuHost.aspx<%@ Page Language="C#" AutoEventWireup="true »CodeFile=“LinkMenuHost.aspx.cs" Inherits=“LinkMenuHost"%><%@ Register TagPrefix="apress" TagName="LinkMenuControl"Src="LinkMenu.ascx" %><html xmlns=""><head runat="server"><body>...<apress:LinkMenuControl id="Menu1" runat="server"OnLinkClicked="LinkClicked" />...</body></html>
  14. 14. Code Behind LinkMenuHost.aspx.csprotected void LinkClicked(object sender, EventArgs e){lblClick.Text = "Click detected.";}
  15. 15. In the current LinkMenu example, no custominformation is passed along with the event. Whenthe LinkClicked event occurs, the web page has noway of knowing what link was clicked.The trick is to switch from the LinkButton.Clickevent to the LinkButton.Command event. TheCommand event automatically gets theCommandArgument that’s defined in the tag.
  16. 16. Also to convey additional information that relates to the event, youneed to create a custom class that derives from EventArgs.The .NET standard for events specifies that every event should usetwo parameters. The first one provides a reference to the control thatsent the event, while the second incorporates any additionalinformation. This additional information is wrapped into a customEventArgs object, which inherits from the System.EventArgs classThe LinkClickedEventArgs class that follows allows the LinkMenuuser control to pass the URL that the user selected through a Urlproperty. It also provides a Cancel property. If set to true, the usercontrol will stop its processing immediately. But if Cancel remainsfalse (the default), the user control will send the user to the new page.
  17. 17. public class LinkClickedEventArgs : EventArgs{public string Url {get; set;}public bool Cancel {get; set;}public LinkClickedEventArgs(string url){Url = url;}}
  18. 18. To use this custom EventArgs class, you need to modify thedefinition of the LinkClicked event so it uses theLinkClickedEventArgs object:// Declaring the LinkClicked eventpublic event EventHandler<LinkClickedEventArgs>LinkClicked;// Defining the LinkClicked eventLinkClickedEventArgs args = newLinkClickedEventArgs((string)e.CommandArgument);// Raising the LinkClicked eventLinkClicked(this, args);
  19. 19. User Control File LinkMenuControl1.ascx<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>
  20. 20. Code Behind File LinkMenuControl.ascx.cspublic 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);}}
  21. 21. Web Page LinkMenuHost.aspx<%@ Page Language="C#" AutoEventWireup="true »CodeFile=“LinkMenuHost.aspx.cs" Inherits=“LinkMenuHost"%><%@ Register TagPrefix="apress" TagName="LinkMenuControl"Src="LinkMenu.ascx" %><html xmlns=""><head runat="server"><body>...<apress:LinkMenuControl1 id="Menu1" runat="server"OnLinkClicked="LinkClicked" />...</body></html>
  22. 22. Code Behind LinkMenuHost.aspx.csprotected 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"]; } }
  23. 23. One of the features of the .NET Framework is GDI+, a set ofclasses 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,
  24. 24. • 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
  25. 25. 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();
  26. 26. The Image.Save() approach demonstrated so far has oneproblem. When you save an image to the response stream,you overwrite whatever information ASP.NET would otherwise use. If you have a web page that includes other content andcontrols, this content won’t appear at all in the final webpage. Instead, the dynamically rendered graphics replace it.Fortunately, this has a simple solution: you can link to adynamically generated image using the <img> tag or theImage web control. But instead of linking your image to afixed image file, link it to the .aspx file that generates thepicture.
  27. 27. 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);