当前位置:首页 > 网络编程 > 软件语言 > .NET > 一个相当独立的.通用分页控件c#源码三

一个相当独立的.通用分页控件c#源码三

点击次数:60 次 发布日期:2008-11-06 08:09:04 作者:源代码网
源代码网推荐
广告载入中
DataView类型和DataTable类型的关系是如此密切,所以构造一个通用性的DataAdapter可能是有意义的,其实只要加入另一个处 理DataTable的构造函数就足够了。遗憾的是,当用户需要不同的功能来处理某个DataTable时,就必须替换或继承整个类。如果我们构造一个使 用同一IdataSourceAdapter的新Builder,用户在选择如何实现适配器时就拥有更多的自由。

  在分页控件中,寻找适当Builder类的操作由一个类型安全的集合完成。

public class AdapterCollection:DictionaryBase
{
private string GetKey(Type key)
{
return key.FullName;
}
public AdapterCollection() {}
publicvoid Add(Type key,AdapterBuilder value)
{
Dictionary.Add(GetKey(key),value);
}
publicbool Contains(Type key)
{
return Dictionary.Contains(GetKey(key));
}
publicvoid Remove(Type key)
{
Dictionary.Remove(GetKey(key));
}
public AdapterBuilder this[Type key]
{
get{return (AdapterBuilder)Dictionary[GetKey(key)];}
set{Dictionary[GetKey(key)]=value;}
}
}

   AdapterCollection依赖于DataSource类型,DataSource通过BoundControl_DataBound巧妙地引 入。这里使用的索引键是Type.FullName方法,确保了每一种类型索引键的唯一性,同时这也把保证每一种类型只有一个Builder的责任赋予了 AdapterCollection。将Builder查找加入BoundControl_DataBound方法,结果如下:

public AdapterCollection Adapters
{
get{return _adapters;}
}

private bool HasParentControlCalledDataBinding
{
get{return _builder != null;}
}

private void BoundControl_DataBound(object sender,System.EventArgs e)
{
if (HasParentControlCalledDataBinding) return;
Type type = sender.GetType();
_datasource = type.GetProperty("DataSource");
if (_datasource == null)
throw new NotSupportedException("分页控件要求表现控件必需包含一个DataSource。");
object data = _datasource.GetGetMethod().Invoke(sender,null);
_builder = Adapters[data.GetType()];
if (_builder == null)
throw new NullReferenceException("没有安装适当的适配器来处理下面的数据源类型:" data.GetType());
_builder.Source = data;

ApplyDataSensitivityRules();
BindParent();
RaiseEvent(DataUpdate,this);
}

  BoundControl_DataBound方法利用HasParentControlCalledDataBinding检查是否已经创建了Builder,如果是,则不再执行寻找适当Builder的操作。Adapters表的初始化在构造函数中完成:

public Pager()
{
SelectedPager=new System.Web.UI.WebControls.Style();
UnselectedPager = new System.Web.UI.WebControls.Style();
_adapters = new AdapterCollection();
_adapters.Add(typeof(DataTable),new DataTableAdapterBuilder());
_adapters.Add(typeof(DataView),new DataViewAdapterBuilder());
}

  最后一个要实现的方法是BindParent,用来处理和返回数据。

private void BindParent()
{
_datasource.GetSetMethod().Invoke(BoundControl,
new object[]{_builder.Adapter.GetPagedData(StartRow,ResultsToShow*CurrentPage)});
}

  这个方法很简单,因为数据处理实际上是由Adapter完成的。这一过程结束后,我们还要用一次Reflection API,不过这一次是设置表现控件的DataSource属性。   三、界面设计

源代码网推荐

源代码网供稿.
网友评论 (0)
会员中心
网络编程
本站推荐
网络编程之精华