Bindable user control (C#) : WebControl « User Control and Master Page « ASP.Net






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.ComponentModel;
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);
    }
  }
}

 








Related examples in the same category

1.SimpleControl extendsing System.Web.UI.WebControls.WebControl
2.SimpleControl extendsing System.Web.UI.WebControls.WebControl (C#)
3.User control based on System.Web.UI.WebControls.Label (C#)
4.User control based on System.Web.UI.WebControls.Label (VB)
5.Bindable user control (VB)