自定义控件(14)编写一个简单的数据绑定控件
程序员文章站
2022-03-04 11:50:32
...
接下来我会定义一个简单的数据绑定控件,把数据库中的数据显示在网页上。
控件代码
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace PZY.BLL.Web.SimpleListView
{
public class SimpleListView : CompositeDataBoundControl
{
protected override HtmlTextWriterTag TagKey
{
get { return HtmlTextWriterTag.Ul; }
}
private ITemplate _itemTemplate;
[TemplateContainer(typeof(ListViewItem))]
[PersistenceMode(PersistenceMode.InnerProperty)]
[Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Advanced)]
public ITemplate ItemTemplate
{
get { return _itemTemplate; }
set { _itemTemplate = value; }
}
protected override int CreateChildControls(IEnumerable dataSource, bool dataBinding)
{
int index = 0;
Controls.Clear();
if (ItemTemplate != null)
{
//数据库中每行数据
foreach (object dataItem in dataSource)
{
ListViewItem listViewItem = new ListViewItem(dataItem, index, index);
ItemTemplate.InstantiateIn(listViewItem);
Controls.Add(listViewItem);
index++;
}
//绑定
DataBind(false);
ChildControlsCreated = true;
}
return index;
}
}
[ToolboxItem(false)]
public class ListViewItem : WebControl, IDataItemContainer
{
private object _dataItem;
private int _index;
private int _displayIndex;
#region IDataItemContainer 成员
public object DataItem
{
get { return _dataItem; }
}
public int DataItemIndex
{
get { return _index; }
}
public int DisplayIndex
{
get { return _displayIndex; }
}
#endregion
protected override HtmlTextWriterTag TagKey
{
get { return HtmlTextWriterTag.Li; }
}
public ListViewItem()
{
}
public ListViewItem(object dataItem, int index, int displayIndex)
{
this._dataItem = dataItem;
this._index = index;
this._displayIndex = displayIndex;
}
}
}
html代码
<div>
<cc1:SimpleListView ID="SimpleListView1" DataSourceID="sdsProducts" runat="server">
<ItemTemplate>
<div>
ISDN:
<asp:Label ID="ISDNLabel" runat="server" Text='<%# Eval("id") %>'></asp:Label>
Title:
<asp:Label ID="TitleLabel" runat="server" Text='<%# Eval("name") %>'></asp:Label>
Author:
<asp:Label ID="AuthorLabel" runat="server" Text='<%# Eval("sort") %>'></asp:Label>
</div>
</ItemTemplate>
</cc1:SimpleListView>
<asp:SqlDataSource ID="sdsProducts" runat="server" ConnectionString="<%$ ConnectionStrings:myConn %>"
OldValuesParameterFormatString="original_{0}" SelectCommand="select Id,Name,Sort from ArticleType">
<UpdateParameters>
<asp:Parameter Name="Id" />
<asp:Parameter Name="Name" />
<asp:Parameter Name="Sort" />
</UpdateParameters>
</asp:SqlDataSource>
</div>
显示结果