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

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

问题描述

简单的问题,我猜.

很长一段时间以来,当我以编程方式绑定我的 ASP.NET 控件时,我一直盲目地遵循一种(据说)常见的模式.即:

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();

但是,如果我将 GridView 设置为通过 DataSourceID 属性绑定到 DataSource 控件,则不需要调用 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;

足够了.

此外,如果您尝试在 ASPX 标记中设置 DataSource 属性,您会看到以下内容:

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

您不能以声明方式设置 DataSource 属性.

You cannot set the DataSource property declaratively.

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

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?

推荐答案

在 ASP.Net 中,让某些数据在页面生命周期的某些点(而不是之前)可用和准备好通常很重要.例如,您可能需要尽早绑定到下拉列表,以便稍后在该列表上设置所选索引.或者,您可能需要稍等片刻来绑定大网格,以减少保持该连接处于活动状态/将数据保留在内存中的时间.

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.

让您显式调用 .DataBind() 方法可以支持频谱两端的场景.

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

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

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