ASP.NET控件开发基础(21)

http://tech.ddvip.com   2007年09月02日    社区交流

内容摘要:既然2.0版本已经提供了数据源控件,你是否有想法,让你原有的控件也升级到同时支持通过设置DataSource属性和数据源控件来获取数据源,这样以后我们就可以省省工作了。这次我们就来讨论这个话题,让旧版本的数据绑定控件支持数据源控件。

  4.获取数据

  接着你便可以在DataBind方法中通过获取到的数据源视图异步获取数据了,本来我们可以调用其ExecuteSelect方法的,可惜我们无法调用此方法,只好异步调用。接着的PerformDataBinding方法跟上篇实现一样。不再列出

  记得在DataBind方法将RequiresDataBinding属性设置为true

/// <summary>
/// 将数据源绑定到控件
/// </summary>
public override void DataBind()
{
  if (!IsBoundUsingDataSourceID)
  {
    OnDataBinding(EventArgs.Empty);
  }
  
  GetData().Select(CreateDataSourceSelectArguments(),
    OnDataSourceViewSelectCallback);
  RequiresDataBinding = false;
  MarkAsDataBound();
}
private void OnDataSourceViewSelectCallback(IEnumerable retrievedData)
{
  if (IsBoundUsingDataSourceID)
  {
    OnDataBinding(EventArgs.Empty);
  }
  PerformDataBinding(retrievedData);
}

  5.重写控件生命周期事件

  其中在OnPreRender方法中调用了EnsureDataBound方法,其他方法的话可以发现在很多不同情况下将RequiresDataBinding和Initialized属性设置为True.做了数据绑定的初始化工作。这里估计我也解释不清楚,大家还是了解下控件的生命周期,了解其事件的使用,再理解吧.

protected override void OnInit(EventArgs e)
{
  base.OnInit(e);
  if (this.Page != null)
  {
    this.Page.PreLoad += new EventHandler(this.OnPagePreLoad);
    if (!base.IsViewStateEnabled && this.Page.IsPostBack)
    {
      this.RequiresDataBinding = true;
    }
  }
}
  
private void OnPagePreLoad(object sender, EventArgs e)
{
  initialized = true;
  if (Page != null)
  {
    Page.PreLoad -= new EventHandler(OnPagePreLoad);
    if (!Page.IsPostBack)
    {
      RequiresDataBinding = true;
    }
    if ((Page.IsPostBack && base.IsViewStateEnabled) && (ViewState["DataBound"] == null))
    {
      RequiresDataBinding = true;
    }
  }
}
  
protected override void OnPreRender(EventArgs e)
{
  EnsureDataBound();
  base.OnPreRender(e);
}
  
protected override void OnLoad(EventArgs e)
{
  this.initialized = true;
  this.ConnectToDataSourceView();
  if (this.Page != null && this.ViewState["DataBound"] == null)
  {
    if (!this.Page.IsPostBack)
    {
      this.RequiresDataBinding = true;
    }
    else if (base.IsViewStateEnabled)
    {
      this.RequiresDataBinding = true;
    }
  }
  base.OnLoad(e);
}

  好了,基本代码的编写就完成了,接着你就可以通过设置DataSource属性手动绑定的形式和设置DataSourceID属性获取数据源的形式获取数据了。

  这篇可以供参考,如果真要这么做的话,几乎每个原有的数据绑定控件都需要重复编写上面这么多代码。相比之下如DataBoundControl类和BaseDataList类都已经帮你完成了上面的工作,在有选择的情况下,我们当然不愿意写上面这么多的代码。所以说上面的这堆代码也只供你参考,能够使用新的基类的话,尽量使用,如果真的需要这么做的话,你就需要这么去改你的数据绑定控件。

  这篇可能讲的不是很详细,大家如果真的有必要这么做的话,可以仔细看看。不足之处还请大家纠正^_^.

责编:豆豆技术应用

正在加载评论...