您应该了解的第一件事是ASP.NET 页面生命周期。一旦您了解了这一点,您将开始了解 Web 表单的机制。它可能看起来很神奇,因为它已经融入了架构,但是一旦你理解了它就真的很简单。
ASP.NET 和 WinForms 中的数据绑定存在很多差异,但基本概念仍然适用。了解数据绑定的最简单方法是查看数据绑定服务器控件的源。
以下是幕后发生的事情:
/// <summary>
/// Binds the data source to the control.
/// </summary>
public override void DataBind()
{
this.PerformSelect();
}
/// <summary>
/// Retrieves data from the associated data source.
/// </summary>
protected override void PerformSelect()
{
//if the control is bound from a datasource control then
//fire the ondatabinding event
if (!this.IsBoundUsingDataSourceID)
this.OnDataBinding(EventArgs.Empty);
//retrive the data source view object and bind the data to the control
this.GetData().Select(CreateDataSourceSelectArguments(), PerformDataBinding);
//mark that the control has been bound to the source
this.RequiresDataBinding = false;
this.MarkAsDataBound();
//fire the on data bound event so it can be
//handled from the parent object
this.OnDataBound(EventArgs.Empty);
}
/// <summary>
/// Binds data from the data source to the control.
/// </summary>
/// <param name="retrievedData"></param>
protected override void PerformDataBinding(IEnumerable retrievedData)
{
//call the base method
base.PerformDataBinding(retrievedData);
//clear all controls and viewstate data and reset
//the viewstate tracking mechanism
this.Controls.Clear();
this.ClearChildViewState();
this.TrackViewState();
//generate all child controls within the hierarchy
this.CreateControlHierarchy(true, retrievedData);
//mark child controls created as true
this.ChildControlsCreated = true;
}
由于控件负责处理所有繁重的工作,因此在前端绑定数据非常容易;只需设置DataSource
并调用DataBind()
上面示例中的方法:
//assign the datasource to the control
GridView1.DataSource = new DataTable("DataSource");
//bind the datasource to the control
GridView1.DataBind();