Custom controls are a very important part of ASP.net, and you can use it to improve the reusability of program code, where a custom control can be reused inside a Web page, a custom control, or a control. The check box control column created by this instance Checkboxcolumn custom controls can be reused anywhere on the site.
This example describes how to create custom controls in asp.net, how to use custom controls, and how to define implementation methods for exposing properties and methods in custom controls.
1. Create a new ASP.net application
Create a new ASP.net Web application in the visual Studio. NET 2003 development environment, named Example_12_5.
2. Create a custom control Checkboxcolumn
Add file CheckItem.cs and file CheckColumn.cs to the application example_12_5. The first file definition class Checkboxitem implements the CheckBox control, and the second file definition class Checkboxcolumn implements the Checkboxcolumn column in the DataGrid control. The class Checkboxitem inherits from the interface ITemplate, where it defines the property name that identifies the control's name, the property that identifies the control's data field DataField, the property that identifies whether the control is read-only ReadOnly, the property that identifies whether the control submits the postback, or not. AutoPostBack and binding the event Binddata () of the control data, the event that is triggered when the control's selection changes, oncheckchanged, and so on. The program code for Class Checkboxitem is as follows:
internal class CheckBoxItem : ITemplate
{
// <summary>
// CheckBoxItem的构造函数
// </summary>
// <param name="editable">控件是否为可编辑</param>
public CheckBoxItem(bool editable,string Name)
{
name = Name;
readOnly = (editable==true)?false:true;
}
// <summary>
// 实例化CheckBox控件,并添加到容器中
// </summary>
// <param name="container">添加控件的容器</param>
void ITemplate.InstantiateIn(Control container)
{
//创建CheckBox控件
CheckBox box = new CheckBox();
//设置控件的属性和事件
box.ID = name;
box.DataBinding += new EventHandler(this.BindData);
box.AutoPostBack = autoPostBack;
box.CheckedChanged += new EventHandler(this.OnCheckChanged);
container.Controls.Add(box);
}
// <summary>
//定义控件的事件CheckChanged
// </summary>
public event EventHandler CheckedChanged;