Monday, October 11, 2004

Adding a Collection Editor property to a custom control

**This sample shows how to add a collection editor window property to a Custom Control**


using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
namespace ControlSampleLibrary
{
// This is my object class.
public class ClassObj
{
private string _ObjectString;
public string ObjectString
{
get { return _ObjectString; }
set { _ObjectString = value; }
}
public ClassObj() { _ObjectString = string.Empty; }
public ClassObj(string s) { _ObjectString = s; }
public override bool Equals(Object obj)
{
if (obj==null GetType() != obj.GetType()) return false;
if (ObjectString!=((ClassObj)obj).ObjectString) return false;
return true;
}
public override int GetHashCode()
{
int x = 0;
return x;
}
}
// This is the modified type-specific collection.
public class ClassColl : System.Collections.CollectionBase
{
public int Add(ClassObj obj) { return List.Add(obj); }
public void Insert(int index, ClassObj obj) { List.Insert(index, obj); }
public void Remove(ClassObj obj) { List.Remove(obj); }
public bool Contains(ClassObj obj) { return List.Contains(obj); }
public void CopyTo(ClassObj[] array, int index) { List.CopyTo(array, index); }

public int IndexOf(object obj)
{
if (obj is int)
return (int)obj;
if (obj is string)
{
for (int i = 0; i < List.Count; i++)
if (((ClassObj)List[i]).ObjectString == obj.ToString())
return i;
return -1;
}
else
{
throw new ArgumentException("Only a string or an integer is permitted for the indexer.");
}
}
public ClassObj this[object obj]
{
get { return (ClassObj)List[IndexOf(obj)]; }
set { List[IndexOf(obj)] = value;}
}
}

// This is the Web server control.
[ToolboxData("<{0}:SampleControl runat=server>")]
public class SampleControl : System.Web.UI.WebControls.WebControl
{
private ClassColl _Col = new ClassColl();
[Category("Things")]
[PersistenceMode(PersistenceMode.InnerProperty)]
public ClassColl Col
{
get { return _Col; }
}
protected override void Render(HtmlTextWriter output)
{
output.Write(this.ToString());
}
}
}

No comments: