简单的问题,我想。
很长一段时间,我在编程式数据绑定ASP.NET控件时盲目地遵循(据称)常见模式。即:
gridView1.DataSource = someList;
gridView1.DataBind();
但是,如果我通过DataSourceID属性将GridView设置为绑定到DataSource 控件,则不需要调用DataBind()。即:
gridView1.DataSourceID = LinqDataSource1;
就足够了。
此外,如果您尝试在ASPX标记中设置DataSource属性,则会遇到以下信息:
您无法以声明方式设置DataSource属性。
我认为这些是相关的,但我仍然难以理解为什么DataBind()是必要的。 DataSource和DataSourceID之间的区别是次要的 - 我可以理解那里发生的一些魔术。真正的问题是为什么DataSource propery setter不能自动导致数据绑定?我们是否有任何想要设置DataSource但不绑定它的场景?
答案 0 :(得分:17)
在ASP.Net中,通常很重要的是在页面生命周期的某些点上提供某些数据并准备就绪,而不是之前。例如,您可能需要提前绑定到下拉列表以允许稍后在该列表上设置所选索引。或者您可能需要等待一段时间来绑定该大型网格,以减少保持该连接活动/保持数据在内存中的时间。
明确调用.DataBind()
方法可以支持频谱两端的场景。
答案 1 :(得分:2)
DataSource是BaseDataBoundControl类的属性。 DataSourceID是DataBoundControl类的一个属性,它继承自BaseDataBoundControl,并且在ASP.NET 2.0之前不存在。
由于DataBoundControl明确用于以列表或表格形式显示数据,并且BaseDataBoundControl无法做出这种假设,因此在设置DataSource时绑定不是自动的,因为控件的类型可能与数据的结构不匹配。
当然,这只是基于MSDN文档的猜测,所以我可能错了。
答案 2 :(得分:0)
我注意到,在没有使用DataBind()的情况下,我的GridView中不会显示任何内容,因此我总是将其包含在代码的这一部分中:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
' TableAdapter object.
' Provide communication between this application and the database.
'-----------------------------------------------------------------
Dim suppliersAdapter As New SuppliersTableAdapter
' Get the data from the TableAdapter into the GridView.
'------------------------------------------------------
GridView1.DataSource = suppliersAdapter.GetSuppliers()
' Display the result set from the TableAdapter in the GridView.
'--------------------------------------------------------------
GridView1.DataBind()
End Sub
请原谅额外的评论,因为我还在学习ASP.Net,这些评论将帮助我更好地学习使用某些陈述的“内容和原因”。
答案 3 :(得分:0)
试试这个:
#ifndef MY_H_
#define MY_H_
namespace A {
void f() {
// do something
}
}
#endif