ASP.Net/User Control and Master Page/WebControl — различия между версиями

Материал из .Net Framework эксперт
Перейти к: навигация, поиск
м (1 версия)
 
(нет различий)

Версия 15:30, 26 мая 2010

Bindable user control (C#)

<%@ Page Language="c#" %>
<%@ Register TagPrefix="Control" Namespace="Control" Assembly="Control" %>
<script runat="server">
  void Page_Load(object sender, EventArgs e)
  {
    listControl.DataSource = new String[] {"Test 1", "Test 2", "Test 3"};
    listControl.DataBind();
  }
</script>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" > 
<html>
<head>
<title>Default</title>
</head>
<body>
<Control:CustomBulletedList  id="listControl" runat="server"/>
</body>
</html>
File: Control.cs
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ruponentModel;
using System.Collections;
using System.Text;
namespace Control
{
  [DefaultProperty("DataSource"),
  ToolboxData("<{0}:CustomBulletedList runat=\"server\"></{0}:CustomBulletedList>")]
  public class CustomBulletedList : System.Web.UI.WebControls.WebControl
  {
    private StringBuilder _html  = new StringBuilder();
    private IEnumerable  _dataSource;
    [Bindable(true),
    Category("Data"),
    DefaultValue(null),
    Description("The data source used to build up the bulleted list."),
    DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
    public IEnumerable DataSource {
      get {
        return _dataSource;
      }
      set {
        _dataSource = value;
      }
    }
    private void CreateBulletedList()
    {
      IEnumerable dataSource = null;
      try {
        dataSource = this._dataSource;
      } catch {
        dataSource = null;
      }
      if (dataSource != null)
      {
        _html.Append("<ul>");
        foreach (object dataObject in dataSource)
        {
          _html.Append("<li>");
          _html.Append(dataObject.ToString());
          _html.Append("</li>");
        }
        _html.Append("</ul>");
      }
    }
    public override void DataBind()
    {
      base.OnDataBinding(EventArgs.Empty);
      CreateBulletedList();
    }
    protected override void Render(HtmlTextWriter output)
    {
      output.Write(_html);
    }
  }
}



Bindable user control (VB)

<%@ Page Language="VB" %>
<%@ Register TagPrefix="Control" Namespace="Control" Assembly="Control" %>
<script language="vb" runat="server">
Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)
  listControl.DataSource = New String() {"Test 1", "Test 2", "Test 3"}
  listControl.DataBind()
End Sub
</script>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<html>
  <head>
    <title>Creating a Databound Control</title>
  </head>
  <body>
    <Control:CustomBulletedList id="listControl" runat="server" />
  </body>
</html>
File: Control.vb
Imports System
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.ruponentModel
Imports System.Collections
Imports System.Text
Namespace Control
    Public Class CustomBulletedList
        Inherits System.Web.UI.WebControls.WebControl
        Private _html As New StringBuilder()
        Private _dataSource As IEnumerable
        Public Property DataSource() As IEnumerable
            Get
                Return _dataSource
            End Get
            Set(ByVal value As IEnumerable)
                _dataSource = value
            End Set
        End Property
        Private Sub CreateBulletedList()
            Dim dataSource As IEnumerable = Nothing
            Try
                dataSource = Me._dataSource
            Catch
            End Try
            If Not (dataSource Is Nothing) Then
                _html.Append("<ul>")
                Dim dataObject As Object
                For Each dataObject In dataSource
                    _html.Append("<li>")
                    _html.Append(dataObject)
                    _html.Append("</li>")
                Next dataObject
                _html.Append("</ul>")
            End If
        End Sub

        Public Overrides Sub DataBind()
            MyBase.OnDataBinding(EventArgs.Empty)
            CreateBulletedList()
        End Sub

        Protected Overrides Sub Render(ByVal output As HtmlTextWriter)
            output.Write(_html)
        End Sub
    End Class
End Namespace



SimpleControl extendsing System.Web.UI.WebControls.WebControl

<%@ Page language="C#" %>
<%@ Register TagPrefix="Control" Namespace="Control" Assembly="Control" %>
<script language="C#" runat="server">
void Page_Load(object sender, EventArgs e)
{
  if (!IsPostBack)
  {
    Random rand = new Random();
    SimpleControl1.Text = rand.Next(1,100).ToString();
  }
}
</script>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<html>
  <body>
    <form id="Form1" method="post" runat="server">
      <Control:SimpleControl id="SimpleControl1" runat="server" />
      <asp:linkbutton text="PostBack test" runat="server" />
      <p>
      Values are not maintained across postbacks. <a href="Control.aspx">Re-load</a>
      </p>
    </form>
  </body>
</html>
File: Control.cs

using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ruponentModel;
namespace Control
{
  [DefaultProperty("Text"), ToolboxData("<{0}:Control runat=server></{0}:Control>")]
  public class SimpleControl : System.Web.UI.WebControls.WebControl
  {
    private string _text;
  
    [Bindable(true), 
      Category("Appearance"), 
      DefaultValue("")] 
    public string Text 
    {
      get
      {
        return _text;
      }
      set
      {
        _text = value;
      }
    }
    protected override void Render(HtmlTextWriter output)
    {
      output.Write(Text);
    }
  }
}



SimpleControl extendsing System.Web.UI.WebControls.WebControl (C#)

<%@ Page language="VB" %>
<%@ Register TagPrefix="Control" Namespace="Control" Assembly="Control" %>
<script runat="server">
Sub Page_Load(Sender As Object, E As EventArgs)
  If Not IsPostBack Then
    Dim RandomGenerator As Random
    RandomGenerator = New Random()
    SimpleControl1.Text = RandomGenerator.Next(1,100)
  End If
End Sub
</script>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<html>
  <head>
    <title>Default</title>
  </head>
  <body>
    <form id="Form1" method="post" runat="server">
      <Control:SimpleControl id="SimpleControl1" runat="server" />
      <asp:linkbutton text="PostBack test" runat="server" />
      <p>
        Values are not maintained across postbacks. <a href="Control.aspx">Re-load</a>
      </p>
    </form>
  </body>
</html>
File: Control.vb
Imports System.ruponentModel
Imports System.Web.UI
Namespace Control
    <DefaultProperty("Text"), ToolboxData("<{0}:Control runat=server></{0}:Control>")> Public Class SimpleControl
        Inherits System.Web.UI.WebControls.WebControl
        Dim _text As String
        <Bindable(True), Category("Appearance"), DefaultValue("")> Property [Text]() As String
            Get
                Return _text
            End Get
            Set(ByVal Value As String)
                _text = Value
            End Set
        End Property
        Protected Overrides Sub Render(ByVal output As System.Web.UI.HtmlTextWriter)
            output.Write([Text])
        End Sub
    End Class
End Namespace



User control based on System.Web.UI.WebControls.Label (C#)

<%@ Page Language="C#" %>
<%@ Register TagPrefix="Control" Namespace="Control" Assembly="Control" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<html>
  <head>
    <title>Custom Controls - Extending Existing Web Controls</title>
  </head>
  <body>
    <form id="Form1" method="post" runat="server">
      <Control:RainbowLabel text="This is a rainbow colored test string" runat="server" /><br/>
      <Control:RainbowLabel EnableRainbowMode="false" text="This is a test string" runat="server" />
    </form>
  </body>
</html>
File: Control.cs
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ruponentModel;
namespace Control
{
  [ToolboxData("<{0}:RainbowLabel runat=server></{0}:RainbowLabel>")]
  public class RainbowLabel : System.Web.UI.WebControls.Label
  {
    public bool EnableRainbowMode
    {
      get { return (ViewState["EnableRainbowMode"] == null)? true : bool.Parse( ViewState["EnableRainbowMode"].ToString() ); }
      set { ViewState["EnableRainbowMode"] = value; }
    }
    protected override void Render(HtmlTextWriter output)
    {
      if (EnableRainbowMode)
        output.Write( ColorizeString(Text) );
      else
        output.Write(Text);
    }
    private string ColorizeString(string input)
    {
      System.Text.StringBuilder output = new System.Text.StringBuilder(input.Length);
      Random rand = new Random(DateTime.Now.Millisecond);
      for (int i = 0; i < input.Length; i++)
      {
        int red = rand.Next(0, 255);
        int green = rand.Next(0, 255);
        int blue = rand.Next(0, 255);
        output.Append("<font color=\"#");
        output.Append( Convert.ToString(red, 16) );
        output.Append( Convert.ToString(green, 16) );
        output.Append( Convert.ToString(blue, 16) );
        output.Append("\">");
        output.Append( input.Substring(i, 1) );
        output.Append("</font>");
      }
      return output.ToString();
    }
  }
}



User control based on System.Web.UI.WebControls.Label (VB)

<%@ Page language="VB" %>
<%@ Register TagPrefix="Control" Namespace="Control" Assembly="Control" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<html>
  <head>
    <title>Extending Existing Web Controls</title>
  </head>
  <body>
    <form id="Form1" method="post" runat="server">
      <Control:RainbowLabel text="This is a rainbow colored test string" runat="server" /><br/>
      <Control:RainbowLabel EnableRainbowMode="false" text="This is a test string" runat="server" />
    </form>
  </body>
</html>
File: Control.vb
Imports System
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.ruponentModel
Namespace Control
    Public Class RainbowLabel
        Inherits System.Web.UI.WebControls.Label
        Public Property EnableRainbowMode() As Boolean
            Get
                If ViewState("EnableRainbowMode") Is Nothing Then
                    Return True
                Else
                    Return Boolean.Parse(CStr(ViewState("EnableRainbowMode")))
                End If
            End Get
            Set(ByVal Value As Boolean)
                ViewState("EnableRainbowMode") = Value
            End Set
        End Property
        Protected Overrides Sub Render(ByVal output As HtmlTextWriter)
            If EnableRainbowMode Then
                output.Write(ColorizeString([Text]))
            Else
                output.Write([Text])
            End If
        End Sub "Render
        Private Function ColorizeString(ByVal input As String) As String
            Dim output As New System.Text.StringBuilder(input.Length)
            Dim rand As Random = New Random(DateTime.Now.Millisecond)
            Dim i As Integer
            For i = 0 To input.Length - 1
                Dim red As Integer = rand.Next(0, 255)
                Dim green As Integer = rand.Next(0, 255)
                Dim blue As Integer = rand.Next(0, 255)
                output.Append("<font color=""#")
                output.Append(Convert.ToString(red, 16))
                output.Append(Convert.ToString(green, 16))
                output.Append(Convert.ToString(blue, 16))
                output.Append(""">")
                output.Append(input.Substring(i, 1))
                output.Append("</font>")
            Next i
            Return output.ToString()
        End Function "ColorizeString
    End Class "RainbowLabel
End Namespace