Thursday, June 19, 2014

Talk into a web user control from a web form.

This is really pretty easy to do, but I only learned how to do it this week. Previously, I would just put stuff into session in the web form and then pull it back out again in the .ascx. In my example to show of the right way to go, I have a simple one page application which just looks like this:

 
 

The markup for the web user control just looks like this.

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="Reverser.ascx.cs"
      Inherits="MyApp.Reverser" %>
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>

 
 

Alright, so it holds a label and nothing more. The code behind for the .ascx on the other hand has some stuff going on inside of it. I made two getsetters which only set. They look like this:

using System;
using System.Drawing;
namespace MyApp
{
   public partial class Reverser : System.Web.UI.UserControl
   {
      public string Bookend
      {
         set
         {
            char[] array = value.ToCharArray();
            string eulav = "";
            for (int i = value.Length - 1; i > -1; i--)
            {
               eulav += array[i];
            }
            Label1.Text = value + " backwards is " + eulav;
         }
      }
      
      public Color Hue
      {
         set { Label1.ForeColor = value; }
      }
      
      protected void Page_Load(object sender, EventArgs e)
      {
      }
   }
}

 
 

I nested the .ascx in a web form which looks like this:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
      Inherits="MyApp.Default" %>
<%@ Register src="Reverser.ascx" tagname="Reverser" tagprefix="uc1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
   <title></title>
</head>
<body>
   <form id="form1" runat="server">
      <uc1:Reverser ID="Reverser1" runat="server" Bookend="god" />
   </form>
</body>
</html>

 
 

Notice how Bookend is specified above? That is one way to talk into the control from the outside. There is another way to do so from the C# side like so:

using System;
using System.Drawing;
namespace MyApp
{
   public partial class Default : System.Web.UI.Page
   {
      protected void Page_Load(object sender, EventArgs e)
      {
         Reverser1.Hue = Color.Firebrick;
      }
   }
}

No comments:

Post a Comment