为什么需要DataBind()方法? [英] Why is the DataBind() method necessary?

查看:148
本文介绍了为什么需要DataBind()方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简单的问题,我猜。

很长一段时间,我以盲目的方式遵循(假定)常用的模式,以编程方式数据绑定我的ASP.NET控件。即:

  gridView1.DataSource = someList; 
gridView1.DataBind();

但是,如果我将GridView设置为绑定到DataSource 控件通过DataSourceID属性,不需要调用DataBind()。即:

  gridView1.DataSourceID = LinqDataSource1; 

足够。



此外,如果您尝试在ASPX标记中设置DataSource属性,您将受到以下问题的欢迎:


您不能以声明方式设置DataSource属性。 p>

我认为这些都是相关的,但是我仍然认为为什么DataBind()是必需的。 DataSource和DataSourceID之间的区别是次要的 - 我可以理解那里发生的一些魔法。真正的问题是:为什么DataSource的固定设备不会自动导致数据绑定?有没有我们想要设置DataSource但不绑定的场景?

解决方案

在ASP.Net中,在页面生命周期中的某些点可以使用某些数据,并且在以前没有准备好某些数据通常很重要。例如,您可能需要提前绑定到下拉列表,以便稍后在该列表中设置所选索引。或者您可能希望稍等一下来绑定大型网格,以减少持有该连接的时间数量,或将数据保存在内存中。



明确地调用 .DataBind()方法可以支持频谱两端的场景。


Simple question, I guess.

For a long time I've blindly followed a (supposedly) common pattern when programmatically databinding my ASP.NET controls. Namely:

gridView1.DataSource = someList;
gridView1.DataBind();

However, if I were setting my GridView to bind to a DataSource control via the DataSourceID property, the call to DataBind() is unnecessary. Namely:

gridView1.DataSourceID = LinqDataSource1;

is sufficient.

Furthermore, if you try to set the DataSource property in ASPX markup, you are greeted with the following:

You cannot set the DataSource property declaratively.

I assume these are related, but I am still stumped as to why DataBind() is necessary. The difference between DataSource and DataSourceID is secondary - I can understand some magic taking place there. The real question is why doesn't the DataSource propery setter cause databinding automatically? Are there any scenarios in which we want to set the DataSource but not bind to it?

解决方案

In ASP.Net, it's often important to have certain data available and ready at certain points in the page life cycle, and not before. For example, you may need to bind to a drop down list early to allow setting the selected index on that list later. Or you might want to wait a bit to bind that large grid to reduce the amount of time you hold that connection active/keep the data in memory.

Having you explicitly call the .DataBind() method makes it possible to support scenarios at both ends of the spectrum.

这篇关于为什么需要DataBind()方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆